vue-i18n.global.js 244 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690
  1. /*!
  2. * vue-i18n v9.13.1
  3. * (c) 2024 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. var VueI18n = (function (exports, vue) {
  7. 'use strict';
  8. /**
  9. * Original Utilities
  10. * written by kazuya kawaguchi
  11. */
  12. const inBrowser = typeof window !== 'undefined';
  13. let mark;
  14. let measure;
  15. {
  16. const perf = inBrowser && window.performance;
  17. if (perf &&
  18. perf.mark &&
  19. perf.measure &&
  20. perf.clearMarks &&
  21. // @ts-ignore browser compat
  22. perf.clearMeasures) {
  23. mark = (tag) => {
  24. perf.mark(tag);
  25. };
  26. measure = (name, startTag, endTag) => {
  27. perf.measure(name, startTag, endTag);
  28. perf.clearMarks(startTag);
  29. perf.clearMarks(endTag);
  30. };
  31. }
  32. }
  33. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  34. /* eslint-disable */
  35. function format$1(message, ...args) {
  36. if (args.length === 1 && isObject(args[0])) {
  37. args = args[0];
  38. }
  39. if (!args || !args.hasOwnProperty) {
  40. args = {};
  41. }
  42. return message.replace(RE_ARGS, (match, identifier) => {
  43. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  44. });
  45. }
  46. const makeSymbol = (name, shareable = false) => !shareable ? Symbol(name) : Symbol.for(name);
  47. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  48. const friendlyJSONstringify = (json) => JSON.stringify(json)
  49. .replace(/\u2028/g, '\\u2028')
  50. .replace(/\u2029/g, '\\u2029')
  51. .replace(/\u0027/g, '\\u0027');
  52. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  53. const isDate = (val) => toTypeString(val) === '[object Date]';
  54. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  55. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  56. const assign = Object.assign;
  57. let _globalThis;
  58. const getGlobalThis = () => {
  59. // prettier-ignore
  60. return (_globalThis ||
  61. (_globalThis =
  62. typeof globalThis !== 'undefined'
  63. ? globalThis
  64. : typeof self !== 'undefined'
  65. ? self
  66. : typeof window !== 'undefined'
  67. ? window
  68. : typeof global !== 'undefined'
  69. ? global
  70. : {}));
  71. };
  72. function escapeHtml(rawText) {
  73. return rawText
  74. .replace(/</g, '&lt;')
  75. .replace(/>/g, '&gt;')
  76. .replace(/"/g, '&quot;')
  77. .replace(/'/g, '&apos;');
  78. }
  79. const hasOwnProperty = Object.prototype.hasOwnProperty;
  80. function hasOwn(obj, key) {
  81. return hasOwnProperty.call(obj, key);
  82. }
  83. /* eslint-enable */
  84. /**
  85. * Useful Utilities By Evan you
  86. * Modified by kazuya kawaguchi
  87. * MIT License
  88. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  89. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  90. */
  91. const isArray = Array.isArray;
  92. const isFunction = (val) => typeof val === 'function';
  93. const isString = (val) => typeof val === 'string';
  94. const isBoolean = (val) => typeof val === 'boolean';
  95. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  96. const isObject = (val) => val !== null && typeof val === 'object';
  97. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  98. const isPromise = (val) => {
  99. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  100. };
  101. const objectToString = Object.prototype.toString;
  102. const toTypeString = (value) => objectToString.call(value);
  103. const isPlainObject = (val) => {
  104. if (!isObject(val))
  105. return false;
  106. const proto = Object.getPrototypeOf(val);
  107. return proto === null || proto.constructor === Object;
  108. };
  109. // for converting list and named values to displayed strings.
  110. const toDisplayString = (val) => {
  111. return val == null
  112. ? ''
  113. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  114. ? JSON.stringify(val, null, 2)
  115. : String(val);
  116. };
  117. function join(items, separator = '') {
  118. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  119. }
  120. const RANGE = 2;
  121. function generateCodeFrame(source, start = 0, end = source.length) {
  122. const lines = source.split(/\r?\n/);
  123. let count = 0;
  124. const res = [];
  125. for (let i = 0; i < lines.length; i++) {
  126. count += lines[i].length + 1;
  127. if (count >= start) {
  128. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  129. if (j < 0 || j >= lines.length)
  130. continue;
  131. const line = j + 1;
  132. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  133. const lineLength = lines[j].length;
  134. if (j === i) {
  135. // push underline
  136. const pad = start - (count - lineLength) + 1;
  137. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  138. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  139. }
  140. else if (j > i) {
  141. if (end > count) {
  142. const length = Math.max(Math.min(end - count, lineLength), 1);
  143. res.push(` | ` + '^'.repeat(length));
  144. }
  145. count += lineLength + 1;
  146. }
  147. }
  148. break;
  149. }
  150. }
  151. return res.join('\n');
  152. }
  153. function incrementer(code) {
  154. let current = code;
  155. return () => ++current;
  156. }
  157. function warn(msg, err) {
  158. if (typeof console !== 'undefined') {
  159. console.warn(`[intlify] ` + msg);
  160. /* istanbul ignore if */
  161. if (err) {
  162. console.warn(err.stack);
  163. }
  164. }
  165. }
  166. const hasWarned = {};
  167. function warnOnce(msg) {
  168. if (!hasWarned[msg]) {
  169. hasWarned[msg] = true;
  170. warn(msg);
  171. }
  172. }
  173. /**
  174. * Event emitter, forked from the below:
  175. * - original repository url: https://github.com/developit/mitt
  176. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  177. * - author: Jason Miller (https://github.com/developit)
  178. * - license: MIT
  179. */
  180. /**
  181. * Create a event emitter
  182. *
  183. * @returns An event emitter
  184. */
  185. function createEmitter() {
  186. const events = new Map();
  187. const emitter = {
  188. events,
  189. on(event, handler) {
  190. const handlers = events.get(event);
  191. const added = handlers && handlers.push(handler);
  192. if (!added) {
  193. events.set(event, [handler]);
  194. }
  195. },
  196. off(event, handler) {
  197. const handlers = events.get(event);
  198. if (handlers) {
  199. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  200. }
  201. },
  202. emit(event, payload) {
  203. (events.get(event) || [])
  204. .slice()
  205. .map(handler => handler(payload));
  206. (events.get('*') || [])
  207. .slice()
  208. .map(handler => handler(event, payload));
  209. }
  210. };
  211. return emitter;
  212. }
  213. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  214. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  215. function deepCopy(src, des) {
  216. // src and des should both be objects, and none of them can be a array
  217. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  218. throw new Error('Invalid value');
  219. }
  220. const stack = [{ src, des }];
  221. while (stack.length) {
  222. const { src, des } = stack.pop();
  223. Object.keys(src).forEach(key => {
  224. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  225. // replace with src[key] when:
  226. // src[key] or des[key] is not an object, or
  227. // src[key] or des[key] is an array
  228. des[key] = src[key];
  229. }
  230. else {
  231. // src[key] and des[key] are both objects, merge them
  232. stack.push({ src: src[key], des: des[key] });
  233. }
  234. });
  235. }
  236. }
  237. function createPosition(line, column, offset) {
  238. return { line, column, offset };
  239. }
  240. function createLocation(start, end, source) {
  241. const loc = { start, end };
  242. if (source != null) {
  243. loc.source = source;
  244. }
  245. return loc;
  246. }
  247. const CompileWarnCodes = {
  248. USE_MODULO_SYNTAX: 1,
  249. __EXTEND_POINT__: 2
  250. };
  251. /** @internal */
  252. const warnMessages$2 = {
  253. [CompileWarnCodes.USE_MODULO_SYNTAX]: `Use modulo before '{{0}}'.`
  254. };
  255. function createCompileWarn(code, loc, ...args) {
  256. const msg = format$1(warnMessages$2[code] || '', ...(args || [])) ;
  257. const message = { message: String(msg), code };
  258. if (loc) {
  259. message.location = loc;
  260. }
  261. return message;
  262. }
  263. const CompileErrorCodes = {
  264. // tokenizer error codes
  265. EXPECTED_TOKEN: 1,
  266. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  267. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  268. UNKNOWN_ESCAPE_SEQUENCE: 4,
  269. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  270. UNBALANCED_CLOSING_BRACE: 6,
  271. UNTERMINATED_CLOSING_BRACE: 7,
  272. EMPTY_PLACEHOLDER: 8,
  273. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  274. INVALID_LINKED_FORMAT: 10,
  275. // parser error codes
  276. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  277. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  278. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  279. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  280. // generator error codes
  281. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  282. // minifier error codes
  283. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  284. // Special value for higher-order compilers to pick up the last code
  285. // to avoid collision of error codes. This should always be kept as the last
  286. // item.
  287. __EXTEND_POINT__: 17
  288. };
  289. /** @internal */
  290. const errorMessages$2 = {
  291. // tokenizer error messages
  292. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  293. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  294. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  295. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  296. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  297. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  298. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  299. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  300. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  301. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  302. // parser error messages
  303. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  304. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  305. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  306. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  307. // generator error messages
  308. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  309. // minimizer error messages
  310. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  311. };
  312. function createCompileError(code, loc, options = {}) {
  313. const { domain, messages, args } = options;
  314. const msg = format$1((messages || errorMessages$2)[code] || '', ...(args || []))
  315. ;
  316. const error = new SyntaxError(String(msg));
  317. error.code = code;
  318. if (loc) {
  319. error.location = loc;
  320. }
  321. error.domain = domain;
  322. return error;
  323. }
  324. /** @internal */
  325. function defaultOnError(error) {
  326. throw error;
  327. }
  328. // eslint-disable-next-line no-useless-escape
  329. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  330. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  331. const CHAR_SP = ' ';
  332. const CHAR_CR = '\r';
  333. const CHAR_LF = '\n';
  334. const CHAR_LS = String.fromCharCode(0x2028);
  335. const CHAR_PS = String.fromCharCode(0x2029);
  336. function createScanner(str) {
  337. const _buf = str;
  338. let _index = 0;
  339. let _line = 1;
  340. let _column = 1;
  341. let _peekOffset = 0;
  342. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  343. const isLF = (index) => _buf[index] === CHAR_LF;
  344. const isPS = (index) => _buf[index] === CHAR_PS;
  345. const isLS = (index) => _buf[index] === CHAR_LS;
  346. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  347. const index = () => _index;
  348. const line = () => _line;
  349. const column = () => _column;
  350. const peekOffset = () => _peekOffset;
  351. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  352. const currentChar = () => charAt(_index);
  353. const currentPeek = () => charAt(_index + _peekOffset);
  354. function next() {
  355. _peekOffset = 0;
  356. if (isLineEnd(_index)) {
  357. _line++;
  358. _column = 0;
  359. }
  360. if (isCRLF(_index)) {
  361. _index++;
  362. }
  363. _index++;
  364. _column++;
  365. return _buf[_index];
  366. }
  367. function peek() {
  368. if (isCRLF(_index + _peekOffset)) {
  369. _peekOffset++;
  370. }
  371. _peekOffset++;
  372. return _buf[_index + _peekOffset];
  373. }
  374. function reset() {
  375. _index = 0;
  376. _line = 1;
  377. _column = 1;
  378. _peekOffset = 0;
  379. }
  380. function resetPeek(offset = 0) {
  381. _peekOffset = offset;
  382. }
  383. function skipToPeek() {
  384. const target = _index + _peekOffset;
  385. // eslint-disable-next-line no-unmodified-loop-condition
  386. while (target !== _index) {
  387. next();
  388. }
  389. _peekOffset = 0;
  390. }
  391. return {
  392. index,
  393. line,
  394. column,
  395. peekOffset,
  396. charAt,
  397. currentChar,
  398. currentPeek,
  399. next,
  400. peek,
  401. reset,
  402. resetPeek,
  403. skipToPeek
  404. };
  405. }
  406. const EOF = undefined;
  407. const DOT = '.';
  408. const LITERAL_DELIMITER = "'";
  409. const ERROR_DOMAIN$3 = 'tokenizer';
  410. function createTokenizer(source, options = {}) {
  411. const location = options.location !== false;
  412. const _scnr = createScanner(source);
  413. const currentOffset = () => _scnr.index();
  414. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  415. const _initLoc = currentPosition();
  416. const _initOffset = currentOffset();
  417. const _context = {
  418. currentType: 14 /* TokenTypes.EOF */,
  419. offset: _initOffset,
  420. startLoc: _initLoc,
  421. endLoc: _initLoc,
  422. lastType: 14 /* TokenTypes.EOF */,
  423. lastOffset: _initOffset,
  424. lastStartLoc: _initLoc,
  425. lastEndLoc: _initLoc,
  426. braceNest: 0,
  427. inLinked: false,
  428. text: ''
  429. };
  430. const context = () => _context;
  431. const { onError } = options;
  432. function emitError(code, pos, offset, ...args) {
  433. const ctx = context();
  434. pos.column += offset;
  435. pos.offset += offset;
  436. if (onError) {
  437. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  438. const err = createCompileError(code, loc, {
  439. domain: ERROR_DOMAIN$3,
  440. args
  441. });
  442. onError(err);
  443. }
  444. }
  445. function getToken(context, type, value) {
  446. context.endLoc = currentPosition();
  447. context.currentType = type;
  448. const token = { type };
  449. if (location) {
  450. token.loc = createLocation(context.startLoc, context.endLoc);
  451. }
  452. if (value != null) {
  453. token.value = value;
  454. }
  455. return token;
  456. }
  457. const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
  458. function eat(scnr, ch) {
  459. if (scnr.currentChar() === ch) {
  460. scnr.next();
  461. return ch;
  462. }
  463. else {
  464. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  465. return '';
  466. }
  467. }
  468. function peekSpaces(scnr) {
  469. let buf = '';
  470. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  471. buf += scnr.currentPeek();
  472. scnr.peek();
  473. }
  474. return buf;
  475. }
  476. function skipSpaces(scnr) {
  477. const buf = peekSpaces(scnr);
  478. scnr.skipToPeek();
  479. return buf;
  480. }
  481. function isIdentifierStart(ch) {
  482. if (ch === EOF) {
  483. return false;
  484. }
  485. const cc = ch.charCodeAt(0);
  486. return ((cc >= 97 && cc <= 122) || // a-z
  487. (cc >= 65 && cc <= 90) || // A-Z
  488. cc === 95 // _
  489. );
  490. }
  491. function isNumberStart(ch) {
  492. if (ch === EOF) {
  493. return false;
  494. }
  495. const cc = ch.charCodeAt(0);
  496. return cc >= 48 && cc <= 57; // 0-9
  497. }
  498. function isNamedIdentifierStart(scnr, context) {
  499. const { currentType } = context;
  500. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  501. return false;
  502. }
  503. peekSpaces(scnr);
  504. const ret = isIdentifierStart(scnr.currentPeek());
  505. scnr.resetPeek();
  506. return ret;
  507. }
  508. function isListIdentifierStart(scnr, context) {
  509. const { currentType } = context;
  510. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  511. return false;
  512. }
  513. peekSpaces(scnr);
  514. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  515. const ret = isNumberStart(ch);
  516. scnr.resetPeek();
  517. return ret;
  518. }
  519. function isLiteralStart(scnr, context) {
  520. const { currentType } = context;
  521. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  522. return false;
  523. }
  524. peekSpaces(scnr);
  525. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  526. scnr.resetPeek();
  527. return ret;
  528. }
  529. function isLinkedDotStart(scnr, context) {
  530. const { currentType } = context;
  531. if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
  532. return false;
  533. }
  534. peekSpaces(scnr);
  535. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  536. scnr.resetPeek();
  537. return ret;
  538. }
  539. function isLinkedModifierStart(scnr, context) {
  540. const { currentType } = context;
  541. if (currentType !== 9 /* TokenTypes.LinkedDot */) {
  542. return false;
  543. }
  544. peekSpaces(scnr);
  545. const ret = isIdentifierStart(scnr.currentPeek());
  546. scnr.resetPeek();
  547. return ret;
  548. }
  549. function isLinkedDelimiterStart(scnr, context) {
  550. const { currentType } = context;
  551. if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
  552. currentType === 12 /* TokenTypes.LinkedModifier */)) {
  553. return false;
  554. }
  555. peekSpaces(scnr);
  556. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  557. scnr.resetPeek();
  558. return ret;
  559. }
  560. function isLinkedReferStart(scnr, context) {
  561. const { currentType } = context;
  562. if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
  563. return false;
  564. }
  565. const fn = () => {
  566. const ch = scnr.currentPeek();
  567. if (ch === "{" /* TokenChars.BraceLeft */) {
  568. return isIdentifierStart(scnr.peek());
  569. }
  570. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  571. ch === "%" /* TokenChars.Modulo */ ||
  572. ch === "|" /* TokenChars.Pipe */ ||
  573. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  574. ch === "." /* TokenChars.LinkedDot */ ||
  575. ch === CHAR_SP ||
  576. !ch) {
  577. return false;
  578. }
  579. else if (ch === CHAR_LF) {
  580. scnr.peek();
  581. return fn();
  582. }
  583. else {
  584. // other characters
  585. return isTextStart(scnr, false);
  586. }
  587. };
  588. const ret = fn();
  589. scnr.resetPeek();
  590. return ret;
  591. }
  592. function isPluralStart(scnr) {
  593. peekSpaces(scnr);
  594. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  595. scnr.resetPeek();
  596. return ret;
  597. }
  598. function detectModuloStart(scnr) {
  599. const spaces = peekSpaces(scnr);
  600. const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
  601. scnr.peek() === "{" /* TokenChars.BraceLeft */;
  602. scnr.resetPeek();
  603. return {
  604. isModulo: ret,
  605. hasSpace: spaces.length > 0
  606. };
  607. }
  608. function isTextStart(scnr, reset = true) {
  609. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  610. const ch = scnr.currentPeek();
  611. if (ch === "{" /* TokenChars.BraceLeft */) {
  612. return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
  613. }
  614. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  615. return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
  616. }
  617. else if (ch === "%" /* TokenChars.Modulo */) {
  618. scnr.peek();
  619. return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
  620. }
  621. else if (ch === "|" /* TokenChars.Pipe */) {
  622. return prev === "%" /* TokenChars.Modulo */ || detectModulo
  623. ? true
  624. : !(prev === CHAR_SP || prev === CHAR_LF);
  625. }
  626. else if (ch === CHAR_SP) {
  627. scnr.peek();
  628. return fn(true, CHAR_SP, detectModulo);
  629. }
  630. else if (ch === CHAR_LF) {
  631. scnr.peek();
  632. return fn(true, CHAR_LF, detectModulo);
  633. }
  634. else {
  635. return true;
  636. }
  637. };
  638. const ret = fn();
  639. reset && scnr.resetPeek();
  640. return ret;
  641. }
  642. function takeChar(scnr, fn) {
  643. const ch = scnr.currentChar();
  644. if (ch === EOF) {
  645. return EOF;
  646. }
  647. if (fn(ch)) {
  648. scnr.next();
  649. return ch;
  650. }
  651. return null;
  652. }
  653. function isIdentifier(ch) {
  654. const cc = ch.charCodeAt(0);
  655. return ((cc >= 97 && cc <= 122) || // a-z
  656. (cc >= 65 && cc <= 90) || // A-Z
  657. (cc >= 48 && cc <= 57) || // 0-9
  658. cc === 95 || // _
  659. cc === 36 // $
  660. );
  661. }
  662. function takeIdentifierChar(scnr) {
  663. return takeChar(scnr, isIdentifier);
  664. }
  665. function isNamedIdentifier(ch) {
  666. const cc = ch.charCodeAt(0);
  667. return ((cc >= 97 && cc <= 122) || // a-z
  668. (cc >= 65 && cc <= 90) || // A-Z
  669. (cc >= 48 && cc <= 57) || // 0-9
  670. cc === 95 || // _
  671. cc === 36 || // $
  672. cc === 45 // -
  673. );
  674. }
  675. function takeNamedIdentifierChar(scnr) {
  676. return takeChar(scnr, isNamedIdentifier);
  677. }
  678. function isDigit(ch) {
  679. const cc = ch.charCodeAt(0);
  680. return cc >= 48 && cc <= 57; // 0-9
  681. }
  682. function takeDigit(scnr) {
  683. return takeChar(scnr, isDigit);
  684. }
  685. function isHexDigit(ch) {
  686. const cc = ch.charCodeAt(0);
  687. return ((cc >= 48 && cc <= 57) || // 0-9
  688. (cc >= 65 && cc <= 70) || // A-F
  689. (cc >= 97 && cc <= 102)); // a-f
  690. }
  691. function takeHexDigit(scnr) {
  692. return takeChar(scnr, isHexDigit);
  693. }
  694. function getDigits(scnr) {
  695. let ch = '';
  696. let num = '';
  697. while ((ch = takeDigit(scnr))) {
  698. num += ch;
  699. }
  700. return num;
  701. }
  702. function readModulo(scnr) {
  703. skipSpaces(scnr);
  704. const ch = scnr.currentChar();
  705. if (ch !== "%" /* TokenChars.Modulo */) {
  706. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  707. }
  708. scnr.next();
  709. return "%" /* TokenChars.Modulo */;
  710. }
  711. function readText(scnr) {
  712. let buf = '';
  713. // eslint-disable-next-line no-constant-condition
  714. while (true) {
  715. const ch = scnr.currentChar();
  716. if (ch === "{" /* TokenChars.BraceLeft */ ||
  717. ch === "}" /* TokenChars.BraceRight */ ||
  718. ch === "@" /* TokenChars.LinkedAlias */ ||
  719. ch === "|" /* TokenChars.Pipe */ ||
  720. !ch) {
  721. break;
  722. }
  723. else if (ch === "%" /* TokenChars.Modulo */) {
  724. if (isTextStart(scnr)) {
  725. buf += ch;
  726. scnr.next();
  727. }
  728. else {
  729. break;
  730. }
  731. }
  732. else if (ch === CHAR_SP || ch === CHAR_LF) {
  733. if (isTextStart(scnr)) {
  734. buf += ch;
  735. scnr.next();
  736. }
  737. else if (isPluralStart(scnr)) {
  738. break;
  739. }
  740. else {
  741. buf += ch;
  742. scnr.next();
  743. }
  744. }
  745. else {
  746. buf += ch;
  747. scnr.next();
  748. }
  749. }
  750. return buf;
  751. }
  752. function readNamedIdentifier(scnr) {
  753. skipSpaces(scnr);
  754. let ch = '';
  755. let name = '';
  756. while ((ch = takeNamedIdentifierChar(scnr))) {
  757. name += ch;
  758. }
  759. if (scnr.currentChar() === EOF) {
  760. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  761. }
  762. return name;
  763. }
  764. function readListIdentifier(scnr) {
  765. skipSpaces(scnr);
  766. let value = '';
  767. if (scnr.currentChar() === '-') {
  768. scnr.next();
  769. value += `-${getDigits(scnr)}`;
  770. }
  771. else {
  772. value += getDigits(scnr);
  773. }
  774. if (scnr.currentChar() === EOF) {
  775. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  776. }
  777. return value;
  778. }
  779. function isLiteral(ch) {
  780. return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  781. }
  782. function readLiteral(scnr) {
  783. skipSpaces(scnr);
  784. // eslint-disable-next-line no-useless-escape
  785. eat(scnr, `\'`);
  786. let ch = '';
  787. let literal = '';
  788. while ((ch = takeChar(scnr, isLiteral))) {
  789. if (ch === '\\') {
  790. literal += readEscapeSequence(scnr);
  791. }
  792. else {
  793. literal += ch;
  794. }
  795. }
  796. const current = scnr.currentChar();
  797. if (current === CHAR_LF || current === EOF) {
  798. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  799. // TODO: Is it correct really?
  800. if (current === CHAR_LF) {
  801. scnr.next();
  802. // eslint-disable-next-line no-useless-escape
  803. eat(scnr, `\'`);
  804. }
  805. return literal;
  806. }
  807. // eslint-disable-next-line no-useless-escape
  808. eat(scnr, `\'`);
  809. return literal;
  810. }
  811. function readEscapeSequence(scnr) {
  812. const ch = scnr.currentChar();
  813. switch (ch) {
  814. case '\\':
  815. case `\'`: // eslint-disable-line no-useless-escape
  816. scnr.next();
  817. return `\\${ch}`;
  818. case 'u':
  819. return readUnicodeEscapeSequence(scnr, ch, 4);
  820. case 'U':
  821. return readUnicodeEscapeSequence(scnr, ch, 6);
  822. default:
  823. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  824. return '';
  825. }
  826. }
  827. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  828. eat(scnr, unicode);
  829. let sequence = '';
  830. for (let i = 0; i < digits; i++) {
  831. const ch = takeHexDigit(scnr);
  832. if (!ch) {
  833. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  834. break;
  835. }
  836. sequence += ch;
  837. }
  838. return `\\${unicode}${sequence}`;
  839. }
  840. function isInvalidIdentifier(ch) {
  841. return (ch !== "{" /* TokenChars.BraceLeft */ &&
  842. ch !== "}" /* TokenChars.BraceRight */ &&
  843. ch !== CHAR_SP &&
  844. ch !== CHAR_LF);
  845. }
  846. function readInvalidIdentifier(scnr) {
  847. skipSpaces(scnr);
  848. let ch = '';
  849. let identifiers = '';
  850. while ((ch = takeChar(scnr, isInvalidIdentifier))) {
  851. identifiers += ch;
  852. }
  853. return identifiers;
  854. }
  855. function readLinkedModifier(scnr) {
  856. let ch = '';
  857. let name = '';
  858. while ((ch = takeIdentifierChar(scnr))) {
  859. name += ch;
  860. }
  861. return name;
  862. }
  863. function readLinkedRefer(scnr) {
  864. const fn = (buf) => {
  865. const ch = scnr.currentChar();
  866. if (ch === "{" /* TokenChars.BraceLeft */ ||
  867. ch === "%" /* TokenChars.Modulo */ ||
  868. ch === "@" /* TokenChars.LinkedAlias */ ||
  869. ch === "|" /* TokenChars.Pipe */ ||
  870. ch === "(" /* TokenChars.ParenLeft */ ||
  871. ch === ")" /* TokenChars.ParenRight */ ||
  872. !ch) {
  873. return buf;
  874. }
  875. else if (ch === CHAR_SP) {
  876. return buf;
  877. }
  878. else if (ch === CHAR_LF || ch === DOT) {
  879. buf += ch;
  880. scnr.next();
  881. return fn(buf);
  882. }
  883. else {
  884. buf += ch;
  885. scnr.next();
  886. return fn(buf);
  887. }
  888. };
  889. return fn('');
  890. }
  891. function readPlural(scnr) {
  892. skipSpaces(scnr);
  893. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  894. skipSpaces(scnr);
  895. return plural;
  896. }
  897. // TODO: We need refactoring of token parsing ...
  898. function readTokenInPlaceholder(scnr, context) {
  899. let token = null;
  900. const ch = scnr.currentChar();
  901. switch (ch) {
  902. case "{" /* TokenChars.BraceLeft */:
  903. if (context.braceNest >= 1) {
  904. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  905. }
  906. scnr.next();
  907. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  908. skipSpaces(scnr);
  909. context.braceNest++;
  910. return token;
  911. case "}" /* TokenChars.BraceRight */:
  912. if (context.braceNest > 0 &&
  913. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  914. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  915. }
  916. scnr.next();
  917. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  918. context.braceNest--;
  919. context.braceNest > 0 && skipSpaces(scnr);
  920. if (context.inLinked && context.braceNest === 0) {
  921. context.inLinked = false;
  922. }
  923. return token;
  924. case "@" /* TokenChars.LinkedAlias */:
  925. if (context.braceNest > 0) {
  926. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  927. }
  928. token = readTokenInLinked(scnr, context) || getEndToken(context);
  929. context.braceNest = 0;
  930. return token;
  931. default: {
  932. let validNamedIdentifier = true;
  933. let validListIdentifier = true;
  934. let validLiteral = true;
  935. if (isPluralStart(scnr)) {
  936. if (context.braceNest > 0) {
  937. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  938. }
  939. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  940. // reset
  941. context.braceNest = 0;
  942. context.inLinked = false;
  943. return token;
  944. }
  945. if (context.braceNest > 0 &&
  946. (context.currentType === 5 /* TokenTypes.Named */ ||
  947. context.currentType === 6 /* TokenTypes.List */ ||
  948. context.currentType === 7 /* TokenTypes.Literal */)) {
  949. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  950. context.braceNest = 0;
  951. return readToken(scnr, context);
  952. }
  953. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  954. token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  955. skipSpaces(scnr);
  956. return token;
  957. }
  958. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  959. token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
  960. skipSpaces(scnr);
  961. return token;
  962. }
  963. if ((validLiteral = isLiteralStart(scnr, context))) {
  964. token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
  965. skipSpaces(scnr);
  966. return token;
  967. }
  968. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  969. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  970. token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  971. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  972. skipSpaces(scnr);
  973. return token;
  974. }
  975. break;
  976. }
  977. }
  978. return token;
  979. }
  980. // TODO: We need refactoring of token parsing ...
  981. function readTokenInLinked(scnr, context) {
  982. const { currentType } = context;
  983. let token = null;
  984. const ch = scnr.currentChar();
  985. if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
  986. currentType === 9 /* TokenTypes.LinkedDot */ ||
  987. currentType === 12 /* TokenTypes.LinkedModifier */ ||
  988. currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
  989. (ch === CHAR_LF || ch === CHAR_SP)) {
  990. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  991. }
  992. switch (ch) {
  993. case "@" /* TokenChars.LinkedAlias */:
  994. scnr.next();
  995. token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  996. context.inLinked = true;
  997. return token;
  998. case "." /* TokenChars.LinkedDot */:
  999. skipSpaces(scnr);
  1000. scnr.next();
  1001. return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  1002. case ":" /* TokenChars.LinkedDelimiter */:
  1003. skipSpaces(scnr);
  1004. scnr.next();
  1005. return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  1006. default:
  1007. if (isPluralStart(scnr)) {
  1008. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  1009. // reset
  1010. context.braceNest = 0;
  1011. context.inLinked = false;
  1012. return token;
  1013. }
  1014. if (isLinkedDotStart(scnr, context) ||
  1015. isLinkedDelimiterStart(scnr, context)) {
  1016. skipSpaces(scnr);
  1017. return readTokenInLinked(scnr, context);
  1018. }
  1019. if (isLinkedModifierStart(scnr, context)) {
  1020. skipSpaces(scnr);
  1021. return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  1022. }
  1023. if (isLinkedReferStart(scnr, context)) {
  1024. skipSpaces(scnr);
  1025. if (ch === "{" /* TokenChars.BraceLeft */) {
  1026. // scan the placeholder
  1027. return readTokenInPlaceholder(scnr, context) || token;
  1028. }
  1029. else {
  1030. return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  1031. }
  1032. }
  1033. if (currentType === 8 /* TokenTypes.LinkedAlias */) {
  1034. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  1035. }
  1036. context.braceNest = 0;
  1037. context.inLinked = false;
  1038. return readToken(scnr, context);
  1039. }
  1040. }
  1041. // TODO: We need refactoring of token parsing ...
  1042. function readToken(scnr, context) {
  1043. let token = { type: 14 /* TokenTypes.EOF */ };
  1044. if (context.braceNest > 0) {
  1045. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1046. }
  1047. if (context.inLinked) {
  1048. return readTokenInLinked(scnr, context) || getEndToken(context);
  1049. }
  1050. const ch = scnr.currentChar();
  1051. switch (ch) {
  1052. case "{" /* TokenChars.BraceLeft */:
  1053. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1054. case "}" /* TokenChars.BraceRight */:
  1055. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  1056. scnr.next();
  1057. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  1058. case "@" /* TokenChars.LinkedAlias */:
  1059. return readTokenInLinked(scnr, context) || getEndToken(context);
  1060. default: {
  1061. if (isPluralStart(scnr)) {
  1062. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  1063. // reset
  1064. context.braceNest = 0;
  1065. context.inLinked = false;
  1066. return token;
  1067. }
  1068. const { isModulo, hasSpace } = detectModuloStart(scnr);
  1069. if (isModulo) {
  1070. return hasSpace
  1071. ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
  1072. : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
  1073. }
  1074. if (isTextStart(scnr)) {
  1075. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  1076. }
  1077. break;
  1078. }
  1079. }
  1080. return token;
  1081. }
  1082. function nextToken() {
  1083. const { currentType, offset, startLoc, endLoc } = _context;
  1084. _context.lastType = currentType;
  1085. _context.lastOffset = offset;
  1086. _context.lastStartLoc = startLoc;
  1087. _context.lastEndLoc = endLoc;
  1088. _context.offset = currentOffset();
  1089. _context.startLoc = currentPosition();
  1090. if (_scnr.currentChar() === EOF) {
  1091. return getToken(_context, 14 /* TokenTypes.EOF */);
  1092. }
  1093. return readToken(_scnr, _context);
  1094. }
  1095. return {
  1096. nextToken,
  1097. currentOffset,
  1098. currentPosition,
  1099. context
  1100. };
  1101. }
  1102. const ERROR_DOMAIN$2 = 'parser';
  1103. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1104. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1105. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1106. switch (match) {
  1107. case `\\\\`:
  1108. return `\\`;
  1109. // eslint-disable-next-line no-useless-escape
  1110. case `\\\'`:
  1111. // eslint-disable-next-line no-useless-escape
  1112. return `\'`;
  1113. default: {
  1114. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1115. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1116. return String.fromCodePoint(codePoint);
  1117. }
  1118. // invalid ...
  1119. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1120. return '�';
  1121. }
  1122. }
  1123. }
  1124. function createParser(options = {}) {
  1125. const location = options.location !== false;
  1126. const { onError, onWarn } = options;
  1127. function emitError(tokenzer, code, start, offset, ...args) {
  1128. const end = tokenzer.currentPosition();
  1129. end.offset += offset;
  1130. end.column += offset;
  1131. if (onError) {
  1132. const loc = location ? createLocation(start, end) : null;
  1133. const err = createCompileError(code, loc, {
  1134. domain: ERROR_DOMAIN$2,
  1135. args
  1136. });
  1137. onError(err);
  1138. }
  1139. }
  1140. function emitWarn(tokenzer, code, start, offset, ...args) {
  1141. const end = tokenzer.currentPosition();
  1142. end.offset += offset;
  1143. end.column += offset;
  1144. if (onWarn) {
  1145. const loc = location ? createLocation(start, end) : null;
  1146. onWarn(createCompileWarn(code, loc, args));
  1147. }
  1148. }
  1149. function startNode(type, offset, loc) {
  1150. const node = { type };
  1151. if (location) {
  1152. node.start = offset;
  1153. node.end = offset;
  1154. node.loc = { start: loc, end: loc };
  1155. }
  1156. return node;
  1157. }
  1158. function endNode(node, offset, pos, type) {
  1159. if (type) {
  1160. node.type = type;
  1161. }
  1162. if (location) {
  1163. node.end = offset;
  1164. if (node.loc) {
  1165. node.loc.end = pos;
  1166. }
  1167. }
  1168. }
  1169. function parseText(tokenizer, value) {
  1170. const context = tokenizer.context();
  1171. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  1172. node.value = value;
  1173. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1174. return node;
  1175. }
  1176. function parseList(tokenizer, index) {
  1177. const context = tokenizer.context();
  1178. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1179. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  1180. node.index = parseInt(index, 10);
  1181. tokenizer.nextToken(); // skip brach right
  1182. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1183. return node;
  1184. }
  1185. function parseNamed(tokenizer, key, modulo) {
  1186. const context = tokenizer.context();
  1187. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1188. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  1189. node.key = key;
  1190. if (modulo === true) {
  1191. node.modulo = true;
  1192. }
  1193. tokenizer.nextToken(); // skip brach right
  1194. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1195. return node;
  1196. }
  1197. function parseLiteral(tokenizer, value) {
  1198. const context = tokenizer.context();
  1199. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1200. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  1201. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1202. tokenizer.nextToken(); // skip brach right
  1203. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1204. return node;
  1205. }
  1206. function parseLinkedModifier(tokenizer) {
  1207. const token = tokenizer.nextToken();
  1208. const context = tokenizer.context();
  1209. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1210. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  1211. if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
  1212. // empty modifier
  1213. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  1214. node.value = '';
  1215. endNode(node, offset, loc);
  1216. return {
  1217. nextConsumeToken: token,
  1218. node
  1219. };
  1220. }
  1221. // check token
  1222. if (token.value == null) {
  1223. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1224. }
  1225. node.value = token.value || '';
  1226. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1227. return {
  1228. node
  1229. };
  1230. }
  1231. function parseLinkedKey(tokenizer, value) {
  1232. const context = tokenizer.context();
  1233. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  1234. node.value = value;
  1235. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1236. return node;
  1237. }
  1238. function parseLinked(tokenizer) {
  1239. const context = tokenizer.context();
  1240. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  1241. let token = tokenizer.nextToken();
  1242. if (token.type === 9 /* TokenTypes.LinkedDot */) {
  1243. const parsed = parseLinkedModifier(tokenizer);
  1244. linkedNode.modifier = parsed.node;
  1245. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1246. }
  1247. // asset check token
  1248. if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
  1249. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1250. }
  1251. token = tokenizer.nextToken();
  1252. // skip brace left
  1253. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  1254. token = tokenizer.nextToken();
  1255. }
  1256. switch (token.type) {
  1257. case 11 /* TokenTypes.LinkedKey */:
  1258. if (token.value == null) {
  1259. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1260. }
  1261. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1262. break;
  1263. case 5 /* TokenTypes.Named */:
  1264. if (token.value == null) {
  1265. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1266. }
  1267. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1268. break;
  1269. case 6 /* TokenTypes.List */:
  1270. if (token.value == null) {
  1271. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1272. }
  1273. linkedNode.key = parseList(tokenizer, token.value || '');
  1274. break;
  1275. case 7 /* TokenTypes.Literal */:
  1276. if (token.value == null) {
  1277. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1278. }
  1279. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1280. break;
  1281. default: {
  1282. // empty key
  1283. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1284. const nextContext = tokenizer.context();
  1285. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1286. emptyLinkedKeyNode.value = '';
  1287. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1288. linkedNode.key = emptyLinkedKeyNode;
  1289. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1290. return {
  1291. nextConsumeToken: token,
  1292. node: linkedNode
  1293. };
  1294. }
  1295. }
  1296. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1297. return {
  1298. node: linkedNode
  1299. };
  1300. }
  1301. function parseMessage(tokenizer) {
  1302. const context = tokenizer.context();
  1303. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1304. ? tokenizer.currentOffset()
  1305. : context.offset;
  1306. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1307. ? context.endLoc
  1308. : context.startLoc;
  1309. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1310. node.items = [];
  1311. let nextToken = null;
  1312. let modulo = null;
  1313. do {
  1314. const token = nextToken || tokenizer.nextToken();
  1315. nextToken = null;
  1316. switch (token.type) {
  1317. case 0 /* TokenTypes.Text */:
  1318. if (token.value == null) {
  1319. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1320. }
  1321. node.items.push(parseText(tokenizer, token.value || ''));
  1322. break;
  1323. case 6 /* TokenTypes.List */:
  1324. if (token.value == null) {
  1325. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1326. }
  1327. node.items.push(parseList(tokenizer, token.value || ''));
  1328. break;
  1329. case 4 /* TokenTypes.Modulo */:
  1330. modulo = true;
  1331. break;
  1332. case 5 /* TokenTypes.Named */:
  1333. if (token.value == null) {
  1334. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1335. }
  1336. node.items.push(parseNamed(tokenizer, token.value || '', !!modulo));
  1337. if (modulo) {
  1338. emitWarn(tokenizer, CompileWarnCodes.USE_MODULO_SYNTAX, context.lastStartLoc, 0, getTokenCaption(token));
  1339. modulo = null;
  1340. }
  1341. break;
  1342. case 7 /* TokenTypes.Literal */:
  1343. if (token.value == null) {
  1344. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1345. }
  1346. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1347. break;
  1348. case 8 /* TokenTypes.LinkedAlias */: {
  1349. const parsed = parseLinked(tokenizer);
  1350. node.items.push(parsed.node);
  1351. nextToken = parsed.nextConsumeToken || null;
  1352. break;
  1353. }
  1354. }
  1355. } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
  1356. context.currentType !== 1 /* TokenTypes.Pipe */);
  1357. // adjust message node loc
  1358. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1359. ? context.lastOffset
  1360. : tokenizer.currentOffset();
  1361. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1362. ? context.lastEndLoc
  1363. : tokenizer.currentPosition();
  1364. endNode(node, endOffset, endLoc);
  1365. return node;
  1366. }
  1367. function parsePlural(tokenizer, offset, loc, msgNode) {
  1368. const context = tokenizer.context();
  1369. let hasEmptyMessage = msgNode.items.length === 0;
  1370. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1371. node.cases = [];
  1372. node.cases.push(msgNode);
  1373. do {
  1374. const msg = parseMessage(tokenizer);
  1375. if (!hasEmptyMessage) {
  1376. hasEmptyMessage = msg.items.length === 0;
  1377. }
  1378. node.cases.push(msg);
  1379. } while (context.currentType !== 14 /* TokenTypes.EOF */);
  1380. if (hasEmptyMessage) {
  1381. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1382. }
  1383. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1384. return node;
  1385. }
  1386. function parseResource(tokenizer) {
  1387. const context = tokenizer.context();
  1388. const { offset, startLoc } = context;
  1389. const msgNode = parseMessage(tokenizer);
  1390. if (context.currentType === 14 /* TokenTypes.EOF */) {
  1391. return msgNode;
  1392. }
  1393. else {
  1394. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1395. }
  1396. }
  1397. function parse(source) {
  1398. const tokenizer = createTokenizer(source, assign({}, options));
  1399. const context = tokenizer.context();
  1400. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1401. if (location && node.loc) {
  1402. node.loc.source = source;
  1403. }
  1404. node.body = parseResource(tokenizer);
  1405. if (options.onCacheKey) {
  1406. node.cacheKey = options.onCacheKey(source);
  1407. }
  1408. // assert whether achieved to EOF
  1409. if (context.currentType !== 14 /* TokenTypes.EOF */) {
  1410. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1411. }
  1412. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1413. return node;
  1414. }
  1415. return { parse };
  1416. }
  1417. function getTokenCaption(token) {
  1418. if (token.type === 14 /* TokenTypes.EOF */) {
  1419. return 'EOF';
  1420. }
  1421. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1422. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1423. }
  1424. function createTransformer(ast, options = {} // eslint-disable-line
  1425. ) {
  1426. const _context = {
  1427. ast,
  1428. helpers: new Set()
  1429. };
  1430. const context = () => _context;
  1431. const helper = (name) => {
  1432. _context.helpers.add(name);
  1433. return name;
  1434. };
  1435. return { context, helper };
  1436. }
  1437. function traverseNodes(nodes, transformer) {
  1438. for (let i = 0; i < nodes.length; i++) {
  1439. traverseNode(nodes[i], transformer);
  1440. }
  1441. }
  1442. function traverseNode(node, transformer) {
  1443. // TODO: if we need pre-hook of transform, should be implemented to here
  1444. switch (node.type) {
  1445. case 1 /* NodeTypes.Plural */:
  1446. traverseNodes(node.cases, transformer);
  1447. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1448. break;
  1449. case 2 /* NodeTypes.Message */:
  1450. traverseNodes(node.items, transformer);
  1451. break;
  1452. case 6 /* NodeTypes.Linked */: {
  1453. const linked = node;
  1454. traverseNode(linked.key, transformer);
  1455. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1456. transformer.helper("type" /* HelperNameMap.TYPE */);
  1457. break;
  1458. }
  1459. case 5 /* NodeTypes.List */:
  1460. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1461. transformer.helper("list" /* HelperNameMap.LIST */);
  1462. break;
  1463. case 4 /* NodeTypes.Named */:
  1464. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1465. transformer.helper("named" /* HelperNameMap.NAMED */);
  1466. break;
  1467. }
  1468. // TODO: if we need post-hook of transform, should be implemented to here
  1469. }
  1470. // transform AST
  1471. function transform(ast, options = {} // eslint-disable-line
  1472. ) {
  1473. const transformer = createTransformer(ast);
  1474. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1475. // traverse
  1476. ast.body && traverseNode(ast.body, transformer);
  1477. // set meta information
  1478. const context = transformer.context();
  1479. ast.helpers = Array.from(context.helpers);
  1480. }
  1481. function optimize(ast) {
  1482. const body = ast.body;
  1483. if (body.type === 2 /* NodeTypes.Message */) {
  1484. optimizeMessageNode(body);
  1485. }
  1486. else {
  1487. body.cases.forEach(c => optimizeMessageNode(c));
  1488. }
  1489. return ast;
  1490. }
  1491. function optimizeMessageNode(message) {
  1492. if (message.items.length === 1) {
  1493. const item = message.items[0];
  1494. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1495. message.static = item.value;
  1496. delete item.value; // optimization for size
  1497. }
  1498. }
  1499. else {
  1500. const values = [];
  1501. for (let i = 0; i < message.items.length; i++) {
  1502. const item = message.items[i];
  1503. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1504. break;
  1505. }
  1506. if (item.value == null) {
  1507. break;
  1508. }
  1509. values.push(item.value);
  1510. }
  1511. if (values.length === message.items.length) {
  1512. message.static = join(values);
  1513. for (let i = 0; i < message.items.length; i++) {
  1514. const item = message.items[i];
  1515. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1516. delete item.value; // optimization for size
  1517. }
  1518. }
  1519. }
  1520. }
  1521. }
  1522. const ERROR_DOMAIN$1 = 'minifier';
  1523. /* eslint-disable @typescript-eslint/no-explicit-any */
  1524. function minify(node) {
  1525. node.t = node.type;
  1526. switch (node.type) {
  1527. case 0 /* NodeTypes.Resource */: {
  1528. const resource = node;
  1529. minify(resource.body);
  1530. resource.b = resource.body;
  1531. delete resource.body;
  1532. break;
  1533. }
  1534. case 1 /* NodeTypes.Plural */: {
  1535. const plural = node;
  1536. const cases = plural.cases;
  1537. for (let i = 0; i < cases.length; i++) {
  1538. minify(cases[i]);
  1539. }
  1540. plural.c = cases;
  1541. delete plural.cases;
  1542. break;
  1543. }
  1544. case 2 /* NodeTypes.Message */: {
  1545. const message = node;
  1546. const items = message.items;
  1547. for (let i = 0; i < items.length; i++) {
  1548. minify(items[i]);
  1549. }
  1550. message.i = items;
  1551. delete message.items;
  1552. if (message.static) {
  1553. message.s = message.static;
  1554. delete message.static;
  1555. }
  1556. break;
  1557. }
  1558. case 3 /* NodeTypes.Text */:
  1559. case 9 /* NodeTypes.Literal */:
  1560. case 8 /* NodeTypes.LinkedModifier */:
  1561. case 7 /* NodeTypes.LinkedKey */: {
  1562. const valueNode = node;
  1563. if (valueNode.value) {
  1564. valueNode.v = valueNode.value;
  1565. delete valueNode.value;
  1566. }
  1567. break;
  1568. }
  1569. case 6 /* NodeTypes.Linked */: {
  1570. const linked = node;
  1571. minify(linked.key);
  1572. linked.k = linked.key;
  1573. delete linked.key;
  1574. if (linked.modifier) {
  1575. minify(linked.modifier);
  1576. linked.m = linked.modifier;
  1577. delete linked.modifier;
  1578. }
  1579. break;
  1580. }
  1581. case 5 /* NodeTypes.List */: {
  1582. const list = node;
  1583. list.i = list.index;
  1584. delete list.index;
  1585. break;
  1586. }
  1587. case 4 /* NodeTypes.Named */: {
  1588. const named = node;
  1589. named.k = named.key;
  1590. delete named.key;
  1591. break;
  1592. }
  1593. default:
  1594. {
  1595. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1596. domain: ERROR_DOMAIN$1,
  1597. args: [node.type]
  1598. });
  1599. }
  1600. }
  1601. delete node.type;
  1602. }
  1603. /* eslint-enable @typescript-eslint/no-explicit-any */
  1604. // eslint-disable-next-line @typescript-eslint/triple-slash-reference
  1605. /// <reference types="source-map-js" />
  1606. const ERROR_DOMAIN = 'parser';
  1607. function createCodeGenerator(ast, options) {
  1608. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1609. const location = options.location !== false;
  1610. const _context = {
  1611. filename,
  1612. code: '',
  1613. column: 1,
  1614. line: 1,
  1615. offset: 0,
  1616. map: undefined,
  1617. breakLineCode,
  1618. needIndent: _needIndent,
  1619. indentLevel: 0
  1620. };
  1621. if (location && ast.loc) {
  1622. _context.source = ast.loc.source;
  1623. }
  1624. const context = () => _context;
  1625. function push(code, node) {
  1626. _context.code += code;
  1627. }
  1628. function _newline(n, withBreakLine = true) {
  1629. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1630. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1631. }
  1632. function indent(withNewLine = true) {
  1633. const level = ++_context.indentLevel;
  1634. withNewLine && _newline(level);
  1635. }
  1636. function deindent(withNewLine = true) {
  1637. const level = --_context.indentLevel;
  1638. withNewLine && _newline(level);
  1639. }
  1640. function newline() {
  1641. _newline(_context.indentLevel);
  1642. }
  1643. const helper = (key) => `_${key}`;
  1644. const needIndent = () => _context.needIndent;
  1645. return {
  1646. context,
  1647. push,
  1648. indent,
  1649. deindent,
  1650. newline,
  1651. helper,
  1652. needIndent
  1653. };
  1654. }
  1655. function generateLinkedNode(generator, node) {
  1656. const { helper } = generator;
  1657. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1658. generateNode(generator, node.key);
  1659. if (node.modifier) {
  1660. generator.push(`, `);
  1661. generateNode(generator, node.modifier);
  1662. generator.push(`, _type`);
  1663. }
  1664. else {
  1665. generator.push(`, undefined, _type`);
  1666. }
  1667. generator.push(`)`);
  1668. }
  1669. function generateMessageNode(generator, node) {
  1670. const { helper, needIndent } = generator;
  1671. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1672. generator.indent(needIndent());
  1673. const length = node.items.length;
  1674. for (let i = 0; i < length; i++) {
  1675. generateNode(generator, node.items[i]);
  1676. if (i === length - 1) {
  1677. break;
  1678. }
  1679. generator.push(', ');
  1680. }
  1681. generator.deindent(needIndent());
  1682. generator.push('])');
  1683. }
  1684. function generatePluralNode(generator, node) {
  1685. const { helper, needIndent } = generator;
  1686. if (node.cases.length > 1) {
  1687. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1688. generator.indent(needIndent());
  1689. const length = node.cases.length;
  1690. for (let i = 0; i < length; i++) {
  1691. generateNode(generator, node.cases[i]);
  1692. if (i === length - 1) {
  1693. break;
  1694. }
  1695. generator.push(', ');
  1696. }
  1697. generator.deindent(needIndent());
  1698. generator.push(`])`);
  1699. }
  1700. }
  1701. function generateResource(generator, node) {
  1702. if (node.body) {
  1703. generateNode(generator, node.body);
  1704. }
  1705. else {
  1706. generator.push('null');
  1707. }
  1708. }
  1709. function generateNode(generator, node) {
  1710. const { helper } = generator;
  1711. switch (node.type) {
  1712. case 0 /* NodeTypes.Resource */:
  1713. generateResource(generator, node);
  1714. break;
  1715. case 1 /* NodeTypes.Plural */:
  1716. generatePluralNode(generator, node);
  1717. break;
  1718. case 2 /* NodeTypes.Message */:
  1719. generateMessageNode(generator, node);
  1720. break;
  1721. case 6 /* NodeTypes.Linked */:
  1722. generateLinkedNode(generator, node);
  1723. break;
  1724. case 8 /* NodeTypes.LinkedModifier */:
  1725. generator.push(JSON.stringify(node.value), node);
  1726. break;
  1727. case 7 /* NodeTypes.LinkedKey */:
  1728. generator.push(JSON.stringify(node.value), node);
  1729. break;
  1730. case 5 /* NodeTypes.List */:
  1731. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1732. break;
  1733. case 4 /* NodeTypes.Named */:
  1734. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1735. break;
  1736. case 9 /* NodeTypes.Literal */:
  1737. generator.push(JSON.stringify(node.value), node);
  1738. break;
  1739. case 3 /* NodeTypes.Text */:
  1740. generator.push(JSON.stringify(node.value), node);
  1741. break;
  1742. default:
  1743. {
  1744. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1745. domain: ERROR_DOMAIN,
  1746. args: [node.type]
  1747. });
  1748. }
  1749. }
  1750. }
  1751. // generate code from AST
  1752. const generate = (ast, options = {} // eslint-disable-line
  1753. ) => {
  1754. const mode = isString(options.mode) ? options.mode : 'normal';
  1755. const filename = isString(options.filename)
  1756. ? options.filename
  1757. : 'message.intl';
  1758. const sourceMap = !!options.sourceMap;
  1759. // prettier-ignore
  1760. const breakLineCode = options.breakLineCode != null
  1761. ? options.breakLineCode
  1762. : mode === 'arrow'
  1763. ? ';'
  1764. : '\n';
  1765. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1766. const helpers = ast.helpers || [];
  1767. const generator = createCodeGenerator(ast, {
  1768. mode,
  1769. filename,
  1770. sourceMap,
  1771. breakLineCode,
  1772. needIndent
  1773. });
  1774. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1775. generator.indent(needIndent);
  1776. if (helpers.length > 0) {
  1777. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1778. generator.newline();
  1779. }
  1780. generator.push(`return `);
  1781. generateNode(generator, ast);
  1782. generator.deindent(needIndent);
  1783. generator.push(`}`);
  1784. delete ast.helpers;
  1785. const { code, map } = generator.context();
  1786. return {
  1787. ast,
  1788. code,
  1789. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1790. };
  1791. };
  1792. function baseCompile$1(source, options = {}) {
  1793. const assignedOptions = assign({}, options);
  1794. const jit = !!assignedOptions.jit;
  1795. const enalbeMinify = !!assignedOptions.minify;
  1796. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1797. // parse source codes
  1798. const parser = createParser(assignedOptions);
  1799. const ast = parser.parse(source);
  1800. if (!jit) {
  1801. // transform ASTs
  1802. transform(ast, assignedOptions);
  1803. // generate javascript codes
  1804. return generate(ast, assignedOptions);
  1805. }
  1806. else {
  1807. // optimize ASTs
  1808. enambeOptimize && optimize(ast);
  1809. // minimize ASTs
  1810. enalbeMinify && minify(ast);
  1811. // In JIT mode, no ast transform, no code generation.
  1812. return { ast, code: '' };
  1813. }
  1814. }
  1815. const pathStateMachine = [];
  1816. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  1817. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  1818. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1819. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1820. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1821. };
  1822. pathStateMachine[1 /* States.IN_PATH */] = {
  1823. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  1824. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  1825. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1826. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1827. };
  1828. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  1829. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  1830. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1831. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  1832. };
  1833. pathStateMachine[3 /* States.IN_IDENT */] = {
  1834. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1835. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1836. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  1837. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  1838. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  1839. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  1840. };
  1841. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  1842. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  1843. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  1844. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  1845. 4 /* States.IN_SUB_PATH */,
  1846. 2 /* Actions.INC_SUB_PATH_DEPTH */
  1847. ],
  1848. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  1849. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1850. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  1851. };
  1852. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  1853. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1854. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1855. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  1856. };
  1857. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  1858. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1859. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1860. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  1861. };
  1862. /**
  1863. * Check if an expression is a literal value.
  1864. */
  1865. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  1866. function isLiteral(exp) {
  1867. return literalValueRE.test(exp);
  1868. }
  1869. /**
  1870. * Strip quotes from a string
  1871. */
  1872. function stripQuotes(str) {
  1873. const a = str.charCodeAt(0);
  1874. const b = str.charCodeAt(str.length - 1);
  1875. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  1876. }
  1877. /**
  1878. * Determine the type of a character in a keypath.
  1879. */
  1880. function getPathCharType(ch) {
  1881. if (ch === undefined || ch === null) {
  1882. return "o" /* PathCharTypes.END_OF_FAIL */;
  1883. }
  1884. const code = ch.charCodeAt(0);
  1885. switch (code) {
  1886. case 0x5b: // [
  1887. case 0x5d: // ]
  1888. case 0x2e: // .
  1889. case 0x22: // "
  1890. case 0x27: // '
  1891. return ch;
  1892. case 0x5f: // _
  1893. case 0x24: // $
  1894. case 0x2d: // -
  1895. return "i" /* PathCharTypes.IDENT */;
  1896. case 0x09: // Tab (HT)
  1897. case 0x0a: // Newline (LF)
  1898. case 0x0d: // Return (CR)
  1899. case 0xa0: // No-break space (NBSP)
  1900. case 0xfeff: // Byte Order Mark (BOM)
  1901. case 0x2028: // Line Separator (LS)
  1902. case 0x2029: // Paragraph Separator (PS)
  1903. return "w" /* PathCharTypes.WORKSPACE */;
  1904. }
  1905. return "i" /* PathCharTypes.IDENT */;
  1906. }
  1907. /**
  1908. * Format a subPath, return its plain form if it is
  1909. * a literal string or number. Otherwise prepend the
  1910. * dynamic indicator (*).
  1911. */
  1912. function formatSubPath(path) {
  1913. const trimmed = path.trim();
  1914. // invalid leading 0
  1915. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  1916. return false;
  1917. }
  1918. return isLiteral(trimmed)
  1919. ? stripQuotes(trimmed)
  1920. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  1921. }
  1922. /**
  1923. * Parse a string path into an array of segments
  1924. */
  1925. function parse(path) {
  1926. const keys = [];
  1927. let index = -1;
  1928. let mode = 0 /* States.BEFORE_PATH */;
  1929. let subPathDepth = 0;
  1930. let c;
  1931. let key; // eslint-disable-line
  1932. let newChar;
  1933. let type;
  1934. let transition;
  1935. let action;
  1936. let typeMap;
  1937. const actions = [];
  1938. actions[0 /* Actions.APPEND */] = () => {
  1939. if (key === undefined) {
  1940. key = newChar;
  1941. }
  1942. else {
  1943. key += newChar;
  1944. }
  1945. };
  1946. actions[1 /* Actions.PUSH */] = () => {
  1947. if (key !== undefined) {
  1948. keys.push(key);
  1949. key = undefined;
  1950. }
  1951. };
  1952. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  1953. actions[0 /* Actions.APPEND */]();
  1954. subPathDepth++;
  1955. };
  1956. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  1957. if (subPathDepth > 0) {
  1958. subPathDepth--;
  1959. mode = 4 /* States.IN_SUB_PATH */;
  1960. actions[0 /* Actions.APPEND */]();
  1961. }
  1962. else {
  1963. subPathDepth = 0;
  1964. if (key === undefined) {
  1965. return false;
  1966. }
  1967. key = formatSubPath(key);
  1968. if (key === false) {
  1969. return false;
  1970. }
  1971. else {
  1972. actions[1 /* Actions.PUSH */]();
  1973. }
  1974. }
  1975. };
  1976. function maybeUnescapeQuote() {
  1977. const nextChar = path[index + 1];
  1978. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  1979. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  1980. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  1981. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  1982. index++;
  1983. newChar = '\\' + nextChar;
  1984. actions[0 /* Actions.APPEND */]();
  1985. return true;
  1986. }
  1987. }
  1988. while (mode !== null) {
  1989. index++;
  1990. c = path[index];
  1991. if (c === '\\' && maybeUnescapeQuote()) {
  1992. continue;
  1993. }
  1994. type = getPathCharType(c);
  1995. typeMap = pathStateMachine[mode];
  1996. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  1997. // check parse error
  1998. if (transition === 8 /* States.ERROR */) {
  1999. return;
  2000. }
  2001. mode = transition[0];
  2002. if (transition[1] !== undefined) {
  2003. action = actions[transition[1]];
  2004. if (action) {
  2005. newChar = c;
  2006. if (action() === false) {
  2007. return;
  2008. }
  2009. }
  2010. }
  2011. // check parse finish
  2012. if (mode === 7 /* States.AFTER_PATH */) {
  2013. return keys;
  2014. }
  2015. }
  2016. }
  2017. // path token cache
  2018. const cache = new Map();
  2019. /**
  2020. * key-value message resolver
  2021. *
  2022. * @remarks
  2023. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  2024. *
  2025. * @param obj - A target object to be resolved with path
  2026. * @param path - A {@link Path | path} to resolve the value of message
  2027. *
  2028. * @returns A resolved {@link PathValue | path value}
  2029. *
  2030. * @VueI18nGeneral
  2031. */
  2032. function resolveWithKeyValue(obj, path) {
  2033. return isObject(obj) ? obj[path] : null;
  2034. }
  2035. /**
  2036. * message resolver
  2037. *
  2038. * @remarks
  2039. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  2040. *
  2041. * @param obj - A target object to be resolved with path
  2042. * @param path - A {@link Path | path} to resolve the value of message
  2043. *
  2044. * @returns A resolved {@link PathValue | path value}
  2045. *
  2046. * @VueI18nGeneral
  2047. */
  2048. function resolveValue(obj, path) {
  2049. // check object
  2050. if (!isObject(obj)) {
  2051. return null;
  2052. }
  2053. // parse path
  2054. let hit = cache.get(path);
  2055. if (!hit) {
  2056. hit = parse(path);
  2057. if (hit) {
  2058. cache.set(path, hit);
  2059. }
  2060. }
  2061. // check hit
  2062. if (!hit) {
  2063. return null;
  2064. }
  2065. // resolve path value
  2066. const len = hit.length;
  2067. let last = obj;
  2068. let i = 0;
  2069. while (i < len) {
  2070. const val = last[hit[i]];
  2071. if (val === undefined) {
  2072. return null;
  2073. }
  2074. if (isFunction(last)) {
  2075. return null;
  2076. }
  2077. last = val;
  2078. i++;
  2079. }
  2080. return last;
  2081. }
  2082. const DEFAULT_MODIFIER = (str) => str;
  2083. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  2084. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  2085. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  2086. const DEFAULT_INTERPOLATE = toDisplayString;
  2087. function pluralDefault(choice, choicesLength) {
  2088. choice = Math.abs(choice);
  2089. if (choicesLength === 2) {
  2090. // prettier-ignore
  2091. return choice
  2092. ? choice > 1
  2093. ? 1
  2094. : 0
  2095. : 1;
  2096. }
  2097. return choice ? Math.min(choice, 2) : 0;
  2098. }
  2099. function getPluralIndex(options) {
  2100. // prettier-ignore
  2101. const index = isNumber(options.pluralIndex)
  2102. ? options.pluralIndex
  2103. : -1;
  2104. // prettier-ignore
  2105. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  2106. ? isNumber(options.named.count)
  2107. ? options.named.count
  2108. : isNumber(options.named.n)
  2109. ? options.named.n
  2110. : index
  2111. : index;
  2112. }
  2113. function normalizeNamed(pluralIndex, props) {
  2114. if (!props.count) {
  2115. props.count = pluralIndex;
  2116. }
  2117. if (!props.n) {
  2118. props.n = pluralIndex;
  2119. }
  2120. }
  2121. function createMessageContext(options = {}) {
  2122. const locale = options.locale;
  2123. const pluralIndex = getPluralIndex(options);
  2124. const pluralRule = isObject(options.pluralRules) &&
  2125. isString(locale) &&
  2126. isFunction(options.pluralRules[locale])
  2127. ? options.pluralRules[locale]
  2128. : pluralDefault;
  2129. const orgPluralRule = isObject(options.pluralRules) &&
  2130. isString(locale) &&
  2131. isFunction(options.pluralRules[locale])
  2132. ? pluralDefault
  2133. : undefined;
  2134. const plural = (messages) => {
  2135. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  2136. };
  2137. const _list = options.list || [];
  2138. const list = (index) => _list[index];
  2139. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2140. const _named = options.named || {};
  2141. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  2142. const named = (key) => _named[key];
  2143. function message(key) {
  2144. // prettier-ignore
  2145. const msg = isFunction(options.messages)
  2146. ? options.messages(key)
  2147. : isObject(options.messages)
  2148. ? options.messages[key]
  2149. : false;
  2150. return !msg
  2151. ? options.parent
  2152. ? options.parent.message(key) // resolve from parent messages
  2153. : DEFAULT_MESSAGE
  2154. : msg;
  2155. }
  2156. const _modifier = (name) => options.modifiers
  2157. ? options.modifiers[name]
  2158. : DEFAULT_MODIFIER;
  2159. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  2160. ? options.processor.normalize
  2161. : DEFAULT_NORMALIZE;
  2162. const interpolate = isPlainObject(options.processor) &&
  2163. isFunction(options.processor.interpolate)
  2164. ? options.processor.interpolate
  2165. : DEFAULT_INTERPOLATE;
  2166. const type = isPlainObject(options.processor) && isString(options.processor.type)
  2167. ? options.processor.type
  2168. : DEFAULT_MESSAGE_DATA_TYPE;
  2169. const linked = (key, ...args) => {
  2170. const [arg1, arg2] = args;
  2171. let type = 'text';
  2172. let modifier = '';
  2173. if (args.length === 1) {
  2174. if (isObject(arg1)) {
  2175. modifier = arg1.modifier || modifier;
  2176. type = arg1.type || type;
  2177. }
  2178. else if (isString(arg1)) {
  2179. modifier = arg1 || modifier;
  2180. }
  2181. }
  2182. else if (args.length === 2) {
  2183. if (isString(arg1)) {
  2184. modifier = arg1 || modifier;
  2185. }
  2186. if (isString(arg2)) {
  2187. type = arg2 || type;
  2188. }
  2189. }
  2190. const ret = message(key)(ctx);
  2191. const msg =
  2192. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  2193. type === 'vnode' && isArray(ret) && modifier
  2194. ? ret[0]
  2195. : ret;
  2196. return modifier ? _modifier(modifier)(msg, type) : msg;
  2197. };
  2198. const ctx = {
  2199. ["list" /* HelperNameMap.LIST */]: list,
  2200. ["named" /* HelperNameMap.NAMED */]: named,
  2201. ["plural" /* HelperNameMap.PLURAL */]: plural,
  2202. ["linked" /* HelperNameMap.LINKED */]: linked,
  2203. ["message" /* HelperNameMap.MESSAGE */]: message,
  2204. ["type" /* HelperNameMap.TYPE */]: type,
  2205. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  2206. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  2207. ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
  2208. };
  2209. return ctx;
  2210. }
  2211. let devtools = null;
  2212. function setDevToolsHook(hook) {
  2213. devtools = hook;
  2214. }
  2215. function initI18nDevTools(i18n, version, meta) {
  2216. // TODO: queue if devtools is undefined
  2217. devtools &&
  2218. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  2219. timestamp: Date.now(),
  2220. i18n,
  2221. version,
  2222. meta
  2223. });
  2224. }
  2225. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  2226. function createDevToolsHook(hook) {
  2227. return (payloads) => devtools && devtools.emit(hook, payloads);
  2228. }
  2229. const code$3 = CompileWarnCodes.__EXTEND_POINT__;
  2230. const inc$3 = incrementer(code$3);
  2231. const CoreWarnCodes = {
  2232. NOT_FOUND_KEY: code$3, // 2
  2233. FALLBACK_TO_TRANSLATE: inc$3(), // 3
  2234. CANNOT_FORMAT_NUMBER: inc$3(), // 4
  2235. FALLBACK_TO_NUMBER_FORMAT: inc$3(), // 5
  2236. CANNOT_FORMAT_DATE: inc$3(), // 6
  2237. FALLBACK_TO_DATE_FORMAT: inc$3(), // 7
  2238. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$3(), // 8
  2239. __EXTEND_POINT__: inc$3() // 9
  2240. };
  2241. /** @internal */
  2242. const warnMessages$1 = {
  2243. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  2244. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  2245. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  2246. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  2247. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  2248. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  2249. [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
  2250. };
  2251. function getWarnMessage$1(code, ...args) {
  2252. return format$1(warnMessages$1[code], ...args);
  2253. }
  2254. const code$2 = CompileErrorCodes.__EXTEND_POINT__;
  2255. const inc$2 = incrementer(code$2);
  2256. const CoreErrorCodes = {
  2257. INVALID_ARGUMENT: code$2, // 17
  2258. INVALID_DATE_ARGUMENT: inc$2(), // 18
  2259. INVALID_ISO_DATE_ARGUMENT: inc$2(), // 19
  2260. NOT_SUPPORT_NON_STRING_MESSAGE: inc$2(), // 20
  2261. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc$2(), // 21
  2262. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc$2(), // 22
  2263. NOT_SUPPORT_LOCALE_TYPE: inc$2(), // 23
  2264. __EXTEND_POINT__: inc$2() // 24
  2265. };
  2266. function createCoreError(code) {
  2267. return createCompileError(code, null, { messages: errorMessages$1 } );
  2268. }
  2269. /** @internal */
  2270. const errorMessages$1 = {
  2271. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  2272. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  2273. 'Make sure your Date represents a valid date.',
  2274. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  2275. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  2276. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  2277. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  2278. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  2279. };
  2280. /** @internal */
  2281. function getLocale(context, options) {
  2282. return options.locale != null
  2283. ? resolveLocale(options.locale)
  2284. : resolveLocale(context.locale);
  2285. }
  2286. let _resolveLocale;
  2287. /** @internal */
  2288. function resolveLocale(locale) {
  2289. if (isString(locale)) {
  2290. return locale;
  2291. }
  2292. else {
  2293. if (isFunction(locale)) {
  2294. if (locale.resolvedOnce && _resolveLocale != null) {
  2295. return _resolveLocale;
  2296. }
  2297. else if (locale.constructor.name === 'Function') {
  2298. const resolve = locale();
  2299. if (isPromise(resolve)) {
  2300. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  2301. }
  2302. return (_resolveLocale = resolve);
  2303. }
  2304. else {
  2305. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  2306. }
  2307. }
  2308. else {
  2309. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  2310. }
  2311. }
  2312. }
  2313. /**
  2314. * Fallback with simple implemenation
  2315. *
  2316. * @remarks
  2317. * A fallback locale function implemented with a simple fallback algorithm.
  2318. *
  2319. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  2320. *
  2321. * @param ctx - A {@link CoreContext | context}
  2322. * @param fallback - A {@link FallbackLocale | fallback locale}
  2323. * @param start - A starting {@link Locale | locale}
  2324. *
  2325. * @returns Fallback locales
  2326. *
  2327. * @VueI18nGeneral
  2328. */
  2329. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  2330. ) {
  2331. // prettier-ignore
  2332. return [...new Set([
  2333. start,
  2334. ...(isArray(fallback)
  2335. ? fallback
  2336. : isObject(fallback)
  2337. ? Object.keys(fallback)
  2338. : isString(fallback)
  2339. ? [fallback]
  2340. : [start])
  2341. ])];
  2342. }
  2343. /**
  2344. * Fallback with locale chain
  2345. *
  2346. * @remarks
  2347. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  2348. *
  2349. * @param ctx - A {@link CoreContext | context}
  2350. * @param fallback - A {@link FallbackLocale | fallback locale}
  2351. * @param start - A starting {@link Locale | locale}
  2352. *
  2353. * @returns Fallback locales
  2354. *
  2355. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  2356. *
  2357. * @VueI18nGeneral
  2358. */
  2359. function fallbackWithLocaleChain(ctx, fallback, start) {
  2360. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  2361. const context = ctx;
  2362. if (!context.__localeChainCache) {
  2363. context.__localeChainCache = new Map();
  2364. }
  2365. let chain = context.__localeChainCache.get(startLocale);
  2366. if (!chain) {
  2367. chain = [];
  2368. // first block defined by start
  2369. let block = [start];
  2370. // while any intervening block found
  2371. while (isArray(block)) {
  2372. block = appendBlockToChain(chain, block, fallback);
  2373. }
  2374. // prettier-ignore
  2375. // last block defined by default
  2376. const defaults = isArray(fallback) || !isPlainObject(fallback)
  2377. ? fallback
  2378. : fallback['default']
  2379. ? fallback['default']
  2380. : null;
  2381. // convert defaults to array
  2382. block = isString(defaults) ? [defaults] : defaults;
  2383. if (isArray(block)) {
  2384. appendBlockToChain(chain, block, false);
  2385. }
  2386. context.__localeChainCache.set(startLocale, chain);
  2387. }
  2388. return chain;
  2389. }
  2390. function appendBlockToChain(chain, block, blocks) {
  2391. let follow = true;
  2392. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2393. const locale = block[i];
  2394. if (isString(locale)) {
  2395. follow = appendLocaleToChain(chain, block[i], blocks);
  2396. }
  2397. }
  2398. return follow;
  2399. }
  2400. function appendLocaleToChain(chain, locale, blocks) {
  2401. let follow;
  2402. const tokens = locale.split('-');
  2403. do {
  2404. const target = tokens.join('-');
  2405. follow = appendItemToChain(chain, target, blocks);
  2406. tokens.splice(-1, 1);
  2407. } while (tokens.length && follow === true);
  2408. return follow;
  2409. }
  2410. function appendItemToChain(chain, target, blocks) {
  2411. let follow = false;
  2412. if (!chain.includes(target)) {
  2413. follow = true;
  2414. if (target) {
  2415. follow = target[target.length - 1] !== '!';
  2416. const locale = target.replace(/!/g, '');
  2417. chain.push(locale);
  2418. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2419. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2420. ) {
  2421. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2422. follow = blocks[locale];
  2423. }
  2424. }
  2425. }
  2426. return follow;
  2427. }
  2428. /* eslint-disable @typescript-eslint/no-explicit-any */
  2429. /**
  2430. * Intlify core-base version
  2431. * @internal
  2432. */
  2433. const VERSION$1 = '9.13.1';
  2434. const NOT_REOSLVED = -1;
  2435. const DEFAULT_LOCALE = 'en-US';
  2436. const MISSING_RESOLVE_VALUE = '';
  2437. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  2438. function getDefaultLinkedModifiers() {
  2439. return {
  2440. upper: (val, type) => {
  2441. // prettier-ignore
  2442. return type === 'text' && isString(val)
  2443. ? val.toUpperCase()
  2444. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2445. ? val.children.toUpperCase()
  2446. : val;
  2447. },
  2448. lower: (val, type) => {
  2449. // prettier-ignore
  2450. return type === 'text' && isString(val)
  2451. ? val.toLowerCase()
  2452. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2453. ? val.children.toLowerCase()
  2454. : val;
  2455. },
  2456. capitalize: (val, type) => {
  2457. // prettier-ignore
  2458. return (type === 'text' && isString(val)
  2459. ? capitalize(val)
  2460. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2461. ? capitalize(val.children)
  2462. : val);
  2463. }
  2464. };
  2465. }
  2466. let _compiler;
  2467. function registerMessageCompiler(compiler) {
  2468. _compiler = compiler;
  2469. }
  2470. let _resolver;
  2471. /**
  2472. * Register the message resolver
  2473. *
  2474. * @param resolver - A {@link MessageResolver} function
  2475. *
  2476. * @VueI18nGeneral
  2477. */
  2478. function registerMessageResolver(resolver) {
  2479. _resolver = resolver;
  2480. }
  2481. let _fallbacker;
  2482. /**
  2483. * Register the locale fallbacker
  2484. *
  2485. * @param fallbacker - A {@link LocaleFallbacker} function
  2486. *
  2487. * @VueI18nGeneral
  2488. */
  2489. function registerLocaleFallbacker(fallbacker) {
  2490. _fallbacker = fallbacker;
  2491. }
  2492. // Additional Meta for Intlify DevTools
  2493. let _additionalMeta = null;
  2494. /* #__NO_SIDE_EFFECTS__ */
  2495. const setAdditionalMeta = (meta) => {
  2496. _additionalMeta = meta;
  2497. };
  2498. /* #__NO_SIDE_EFFECTS__ */
  2499. const getAdditionalMeta = () => _additionalMeta;
  2500. let _fallbackContext = null;
  2501. const setFallbackContext = (context) => {
  2502. _fallbackContext = context;
  2503. };
  2504. const getFallbackContext = () => _fallbackContext;
  2505. // ID for CoreContext
  2506. let _cid = 0;
  2507. function createCoreContext(options = {}) {
  2508. // setup options
  2509. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  2510. const version = isString(options.version) ? options.version : VERSION$1;
  2511. const locale = isString(options.locale) || isFunction(options.locale)
  2512. ? options.locale
  2513. : DEFAULT_LOCALE;
  2514. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  2515. const fallbackLocale = isArray(options.fallbackLocale) ||
  2516. isPlainObject(options.fallbackLocale) ||
  2517. isString(options.fallbackLocale) ||
  2518. options.fallbackLocale === false
  2519. ? options.fallbackLocale
  2520. : _locale;
  2521. const messages = isPlainObject(options.messages)
  2522. ? options.messages
  2523. : { [_locale]: {} };
  2524. const datetimeFormats = isPlainObject(options.datetimeFormats)
  2525. ? options.datetimeFormats
  2526. : { [_locale]: {} }
  2527. ;
  2528. const numberFormats = isPlainObject(options.numberFormats)
  2529. ? options.numberFormats
  2530. : { [_locale]: {} }
  2531. ;
  2532. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  2533. const pluralRules = options.pluralRules || {};
  2534. const missing = isFunction(options.missing) ? options.missing : null;
  2535. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2536. ? options.missingWarn
  2537. : true;
  2538. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2539. ? options.fallbackWarn
  2540. : true;
  2541. const fallbackFormat = !!options.fallbackFormat;
  2542. const unresolving = !!options.unresolving;
  2543. const postTranslation = isFunction(options.postTranslation)
  2544. ? options.postTranslation
  2545. : null;
  2546. const processor = isPlainObject(options.processor) ? options.processor : null;
  2547. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2548. ? options.warnHtmlMessage
  2549. : true;
  2550. const escapeParameter = !!options.escapeParameter;
  2551. const messageCompiler = isFunction(options.messageCompiler)
  2552. ? options.messageCompiler
  2553. : _compiler;
  2554. const messageResolver = isFunction(options.messageResolver)
  2555. ? options.messageResolver
  2556. : _resolver || resolveWithKeyValue;
  2557. const localeFallbacker = isFunction(options.localeFallbacker)
  2558. ? options.localeFallbacker
  2559. : _fallbacker || fallbackWithSimple;
  2560. const fallbackContext = isObject(options.fallbackContext)
  2561. ? options.fallbackContext
  2562. : undefined;
  2563. // setup internal options
  2564. const internalOptions = options;
  2565. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  2566. ? internalOptions.__datetimeFormatters
  2567. : new Map()
  2568. ;
  2569. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  2570. ? internalOptions.__numberFormatters
  2571. : new Map()
  2572. ;
  2573. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  2574. _cid++;
  2575. const context = {
  2576. version,
  2577. cid: _cid,
  2578. locale,
  2579. fallbackLocale,
  2580. messages,
  2581. modifiers,
  2582. pluralRules,
  2583. missing,
  2584. missingWarn,
  2585. fallbackWarn,
  2586. fallbackFormat,
  2587. unresolving,
  2588. postTranslation,
  2589. processor,
  2590. warnHtmlMessage,
  2591. escapeParameter,
  2592. messageCompiler,
  2593. messageResolver,
  2594. localeFallbacker,
  2595. fallbackContext,
  2596. onWarn,
  2597. __meta
  2598. };
  2599. {
  2600. context.datetimeFormats = datetimeFormats;
  2601. context.numberFormats = numberFormats;
  2602. context.__datetimeFormatters = __datetimeFormatters;
  2603. context.__numberFormatters = __numberFormatters;
  2604. }
  2605. // for vue-devtools timeline event
  2606. {
  2607. context.__v_emitter =
  2608. internalOptions.__v_emitter != null
  2609. ? internalOptions.__v_emitter
  2610. : undefined;
  2611. }
  2612. // NOTE: experimental !!
  2613. {
  2614. initI18nDevTools(context, version, __meta);
  2615. }
  2616. return context;
  2617. }
  2618. /** @internal */
  2619. function isTranslateFallbackWarn(fallback, key) {
  2620. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2621. }
  2622. /** @internal */
  2623. function isTranslateMissingWarn(missing, key) {
  2624. return missing instanceof RegExp ? missing.test(key) : missing;
  2625. }
  2626. /** @internal */
  2627. function handleMissing(context, key, locale, missingWarn, type) {
  2628. const { missing, onWarn } = context;
  2629. // for vue-devtools timeline event
  2630. {
  2631. const emitter = context.__v_emitter;
  2632. if (emitter) {
  2633. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  2634. locale,
  2635. key,
  2636. type,
  2637. groupId: `${type}:${key}`
  2638. });
  2639. }
  2640. }
  2641. if (missing !== null) {
  2642. const ret = missing(context, locale, key, type);
  2643. return isString(ret) ? ret : key;
  2644. }
  2645. else {
  2646. if (isTranslateMissingWarn(missingWarn, key)) {
  2647. onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  2648. }
  2649. return key;
  2650. }
  2651. }
  2652. /** @internal */
  2653. function updateFallbackLocale(ctx, locale, fallback) {
  2654. const context = ctx;
  2655. context.__localeChainCache = new Map();
  2656. ctx.localeFallbacker(ctx, fallback, locale);
  2657. }
  2658. /** @internal */
  2659. function isAlmostSameLocale(locale, compareLocale) {
  2660. if (locale === compareLocale)
  2661. return false;
  2662. return locale.split('-')[0] === compareLocale.split('-')[0];
  2663. }
  2664. /** @internal */
  2665. function isImplicitFallback(targetLocale, locales) {
  2666. const index = locales.indexOf(targetLocale);
  2667. if (index === -1) {
  2668. return false;
  2669. }
  2670. for (let i = index + 1; i < locales.length; i++) {
  2671. if (isAlmostSameLocale(targetLocale, locales[i])) {
  2672. return true;
  2673. }
  2674. }
  2675. return false;
  2676. }
  2677. /* eslint-enable @typescript-eslint/no-explicit-any */
  2678. function format(ast) {
  2679. const msg = (ctx) => formatParts(ctx, ast);
  2680. return msg;
  2681. }
  2682. function formatParts(ctx, ast) {
  2683. const body = ast.b || ast.body;
  2684. if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
  2685. const plural = body;
  2686. const cases = plural.c || plural.cases;
  2687. return ctx.plural(cases.reduce((messages, c) => [
  2688. ...messages,
  2689. formatMessageParts(ctx, c)
  2690. ], []));
  2691. }
  2692. else {
  2693. return formatMessageParts(ctx, body);
  2694. }
  2695. }
  2696. function formatMessageParts(ctx, node) {
  2697. const _static = node.s || node.static;
  2698. if (_static) {
  2699. return ctx.type === 'text'
  2700. ? _static
  2701. : ctx.normalize([_static]);
  2702. }
  2703. else {
  2704. const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  2705. return ctx.normalize(messages);
  2706. }
  2707. }
  2708. function formatMessagePart(ctx, node) {
  2709. const type = node.t || node.type;
  2710. switch (type) {
  2711. case 3 /* NodeTypes.Text */: {
  2712. const text = node;
  2713. return (text.v || text.value);
  2714. }
  2715. case 9 /* NodeTypes.Literal */: {
  2716. const literal = node;
  2717. return (literal.v || literal.value);
  2718. }
  2719. case 4 /* NodeTypes.Named */: {
  2720. const named = node;
  2721. return ctx.interpolate(ctx.named(named.k || named.key));
  2722. }
  2723. case 5 /* NodeTypes.List */: {
  2724. const list = node;
  2725. return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
  2726. }
  2727. case 6 /* NodeTypes.Linked */: {
  2728. const linked = node;
  2729. const modifier = linked.m || linked.modifier;
  2730. return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  2731. }
  2732. case 7 /* NodeTypes.LinkedKey */: {
  2733. const linkedKey = node;
  2734. return (linkedKey.v || linkedKey.value);
  2735. }
  2736. case 8 /* NodeTypes.LinkedModifier */: {
  2737. const linkedModifier = node;
  2738. return (linkedModifier.v || linkedModifier.value);
  2739. }
  2740. default:
  2741. throw new Error(`unhandled node type on format message part: ${type}`);
  2742. }
  2743. }
  2744. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  2745. function checkHtmlMessage(source, warnHtmlMessage) {
  2746. if (warnHtmlMessage && detectHtmlTag(source)) {
  2747. warn(format$1(WARN_MESSAGE, { source }));
  2748. }
  2749. }
  2750. const defaultOnCacheKey = (message) => message;
  2751. let compileCache = Object.create(null);
  2752. function onCompileWarn(_warn) {
  2753. if (_warn.code === CompileWarnCodes.USE_MODULO_SYNTAX) {
  2754. warn(`The use of named interpolation with modulo syntax is deprecated. ` +
  2755. `It will be removed in v10.\n` +
  2756. `reference: https://vue-i18n.intlify.dev/guide/essentials/syntax#rails-i18n-format \n` +
  2757. `(message compiler warning message: ${_warn.message})`);
  2758. }
  2759. }
  2760. const isMessageAST = (val) => isObject(val) &&
  2761. (val.t === 0 || val.type === 0) &&
  2762. ('b' in val || 'body' in val);
  2763. function baseCompile(message, options = {}) {
  2764. // error detecting on compile
  2765. let detectError = false;
  2766. const onError = options.onError || defaultOnError;
  2767. options.onError = (err) => {
  2768. detectError = true;
  2769. onError(err);
  2770. };
  2771. // compile with mesasge-compiler
  2772. return { ...baseCompile$1(message, options), detectError };
  2773. }
  2774. function compile(message, context) {
  2775. // set onWarn
  2776. {
  2777. context.onWarn = onCompileWarn;
  2778. }
  2779. if (isString(message)) {
  2780. // check HTML message
  2781. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  2782. ? context.warnHtmlMessage
  2783. : true;
  2784. checkHtmlMessage(message, warnHtmlMessage);
  2785. // check caches
  2786. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  2787. const cacheKey = onCacheKey(message);
  2788. const cached = compileCache[cacheKey];
  2789. if (cached) {
  2790. return cached;
  2791. }
  2792. // compile with JIT mode
  2793. const { ast, detectError } = baseCompile(message, {
  2794. ...context,
  2795. location: true,
  2796. jit: true
  2797. });
  2798. // compose message function from AST
  2799. const msg = format(ast);
  2800. // if occurred compile error, don't cache
  2801. return !detectError
  2802. ? (compileCache[cacheKey] = msg)
  2803. : msg;
  2804. }
  2805. else {
  2806. if (!isMessageAST(message)) {
  2807. warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  2808. return (() => message);
  2809. }
  2810. // AST case (passed from bundler)
  2811. const cacheKey = message.cacheKey;
  2812. if (cacheKey) {
  2813. const cached = compileCache[cacheKey];
  2814. if (cached) {
  2815. return cached;
  2816. }
  2817. // compose message function from message (AST)
  2818. return (compileCache[cacheKey] =
  2819. format(message));
  2820. }
  2821. else {
  2822. return format(message);
  2823. }
  2824. }
  2825. }
  2826. const NOOP_MESSAGE_FUNCTION = () => '';
  2827. const isMessageFunction = (val) => isFunction(val);
  2828. // implementation of `translate` function
  2829. function translate(context, ...args) {
  2830. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  2831. const [key, options] = parseTranslateArgs(...args);
  2832. const missingWarn = isBoolean(options.missingWarn)
  2833. ? options.missingWarn
  2834. : context.missingWarn;
  2835. const fallbackWarn = isBoolean(options.fallbackWarn)
  2836. ? options.fallbackWarn
  2837. : context.fallbackWarn;
  2838. const escapeParameter = isBoolean(options.escapeParameter)
  2839. ? options.escapeParameter
  2840. : context.escapeParameter;
  2841. const resolvedMessage = !!options.resolvedMessage;
  2842. // prettier-ignore
  2843. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  2844. ? !isBoolean(options.default)
  2845. ? options.default
  2846. : (!messageCompiler ? () => key : key)
  2847. : fallbackFormat // default by `fallbackFormat` option
  2848. ? (!messageCompiler ? () => key : key)
  2849. : '';
  2850. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  2851. const locale = getLocale(context, options);
  2852. // escape params
  2853. escapeParameter && escapeParams(options);
  2854. // resolve message format
  2855. // eslint-disable-next-line prefer-const
  2856. let [formatScope, targetLocale, message] = !resolvedMessage
  2857. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  2858. : [
  2859. key,
  2860. locale,
  2861. messages[locale] || {}
  2862. ];
  2863. // NOTE:
  2864. // Fix to work around `ssrTransfrom` bug in Vite.
  2865. // https://github.com/vitejs/vite/issues/4306
  2866. // To get around this, use temporary variables.
  2867. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  2868. let format = formatScope;
  2869. // if you use default message, set it as message format!
  2870. let cacheBaseKey = key;
  2871. if (!resolvedMessage &&
  2872. !(isString(format) ||
  2873. isMessageAST(format) ||
  2874. isMessageFunction(format))) {
  2875. if (enableDefaultMsg) {
  2876. format = defaultMsgOrKey;
  2877. cacheBaseKey = format;
  2878. }
  2879. }
  2880. // checking message format and target locale
  2881. if (!resolvedMessage &&
  2882. (!(isString(format) ||
  2883. isMessageAST(format) ||
  2884. isMessageFunction(format)) ||
  2885. !isString(targetLocale))) {
  2886. return unresolving ? NOT_REOSLVED : key;
  2887. }
  2888. // TODO: refactor
  2889. if (isString(format) && context.messageCompiler == null) {
  2890. warn(`The message format compilation is not supported in this build. ` +
  2891. `Because message compiler isn't included. ` +
  2892. `You need to pre-compilation all message format. ` +
  2893. `So translate function return '${key}'.`);
  2894. return key;
  2895. }
  2896. // setup compile error detecting
  2897. let occurred = false;
  2898. const onError = () => {
  2899. occurred = true;
  2900. };
  2901. // compile message format
  2902. const msg = !isMessageFunction(format)
  2903. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  2904. : format;
  2905. // if occurred compile error, return the message format
  2906. if (occurred) {
  2907. return format;
  2908. }
  2909. // evaluate message with context
  2910. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  2911. const msgContext = createMessageContext(ctxOptions);
  2912. const messaged = evaluateMessage(context, msg, msgContext);
  2913. // if use post translation option, proceed it with handler
  2914. const ret = postTranslation
  2915. ? postTranslation(messaged, key)
  2916. : messaged;
  2917. // NOTE: experimental !!
  2918. {
  2919. // prettier-ignore
  2920. const payloads = {
  2921. timestamp: Date.now(),
  2922. key: isString(key)
  2923. ? key
  2924. : isMessageFunction(format)
  2925. ? format.key
  2926. : '',
  2927. locale: targetLocale || (isMessageFunction(format)
  2928. ? format.locale
  2929. : ''),
  2930. format: isString(format)
  2931. ? format
  2932. : isMessageFunction(format)
  2933. ? format.source
  2934. : '',
  2935. message: ret
  2936. };
  2937. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  2938. translateDevTools(payloads);
  2939. }
  2940. return ret;
  2941. }
  2942. function escapeParams(options) {
  2943. if (isArray(options.list)) {
  2944. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  2945. }
  2946. else if (isObject(options.named)) {
  2947. Object.keys(options.named).forEach(key => {
  2948. if (isString(options.named[key])) {
  2949. options.named[key] = escapeHtml(options.named[key]);
  2950. }
  2951. });
  2952. }
  2953. }
  2954. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  2955. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  2956. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  2957. let message = {};
  2958. let targetLocale;
  2959. let format = null;
  2960. let from = locale;
  2961. let to = null;
  2962. const type = 'translate';
  2963. for (let i = 0; i < locales.length; i++) {
  2964. targetLocale = to = locales[i];
  2965. if (locale !== targetLocale &&
  2966. !isAlmostSameLocale(locale, targetLocale) &&
  2967. isTranslateFallbackWarn(fallbackWarn, key)) {
  2968. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  2969. key,
  2970. target: targetLocale
  2971. }));
  2972. }
  2973. // for vue-devtools timeline event
  2974. if (locale !== targetLocale) {
  2975. const emitter = context.__v_emitter;
  2976. if (emitter) {
  2977. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  2978. type,
  2979. key,
  2980. from,
  2981. to,
  2982. groupId: `${type}:${key}`
  2983. });
  2984. }
  2985. }
  2986. message =
  2987. messages[targetLocale] || {};
  2988. // for vue-devtools timeline event
  2989. let start = null;
  2990. let startTag;
  2991. let endTag;
  2992. if (inBrowser) {
  2993. start = window.performance.now();
  2994. startTag = 'intlify-message-resolve-start';
  2995. endTag = 'intlify-message-resolve-end';
  2996. mark && mark(startTag);
  2997. }
  2998. if ((format = resolveValue(message, key)) === null) {
  2999. // if null, resolve with object key path
  3000. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  3001. }
  3002. // for vue-devtools timeline event
  3003. if (inBrowser) {
  3004. const end = window.performance.now();
  3005. const emitter = context.__v_emitter;
  3006. if (emitter && start && format) {
  3007. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  3008. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  3009. key,
  3010. message: format,
  3011. time: end - start,
  3012. groupId: `${type}:${key}`
  3013. });
  3014. }
  3015. if (startTag && endTag && mark && measure) {
  3016. mark(endTag);
  3017. measure('intlify message resolve', startTag, endTag);
  3018. }
  3019. }
  3020. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  3021. break;
  3022. }
  3023. if (!isImplicitFallback(targetLocale, locales)) {
  3024. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3025. key, targetLocale, missingWarn, type);
  3026. if (missingRet !== key) {
  3027. format = missingRet;
  3028. }
  3029. }
  3030. from = to;
  3031. }
  3032. return [format, targetLocale, message];
  3033. }
  3034. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  3035. const { messageCompiler, warnHtmlMessage } = context;
  3036. if (isMessageFunction(format)) {
  3037. const msg = format;
  3038. msg.locale = msg.locale || targetLocale;
  3039. msg.key = msg.key || key;
  3040. return msg;
  3041. }
  3042. if (messageCompiler == null) {
  3043. const msg = (() => format);
  3044. msg.locale = targetLocale;
  3045. msg.key = key;
  3046. return msg;
  3047. }
  3048. // for vue-devtools timeline event
  3049. let start = null;
  3050. let startTag;
  3051. let endTag;
  3052. if (inBrowser) {
  3053. start = window.performance.now();
  3054. startTag = 'intlify-message-compilation-start';
  3055. endTag = 'intlify-message-compilation-end';
  3056. mark && mark(startTag);
  3057. }
  3058. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  3059. // for vue-devtools timeline event
  3060. if (inBrowser) {
  3061. const end = window.performance.now();
  3062. const emitter = context.__v_emitter;
  3063. if (emitter && start) {
  3064. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  3065. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  3066. message: format,
  3067. time: end - start,
  3068. groupId: `${'translate'}:${key}`
  3069. });
  3070. }
  3071. if (startTag && endTag && mark && measure) {
  3072. mark(endTag);
  3073. measure('intlify message compilation', startTag, endTag);
  3074. }
  3075. }
  3076. msg.locale = targetLocale;
  3077. msg.key = key;
  3078. msg.source = format;
  3079. return msg;
  3080. }
  3081. function evaluateMessage(context, msg, msgCtx) {
  3082. // for vue-devtools timeline event
  3083. let start = null;
  3084. let startTag;
  3085. let endTag;
  3086. if (inBrowser) {
  3087. start = window.performance.now();
  3088. startTag = 'intlify-message-evaluation-start';
  3089. endTag = 'intlify-message-evaluation-end';
  3090. mark && mark(startTag);
  3091. }
  3092. const messaged = msg(msgCtx);
  3093. // for vue-devtools timeline event
  3094. if (inBrowser) {
  3095. const end = window.performance.now();
  3096. const emitter = context.__v_emitter;
  3097. if (emitter && start) {
  3098. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  3099. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  3100. value: messaged,
  3101. time: end - start,
  3102. groupId: `${'translate'}:${msg.key}`
  3103. });
  3104. }
  3105. if (startTag && endTag && mark && measure) {
  3106. mark(endTag);
  3107. measure('intlify message evaluation', startTag, endTag);
  3108. }
  3109. }
  3110. return messaged;
  3111. }
  3112. /** @internal */
  3113. function parseTranslateArgs(...args) {
  3114. const [arg1, arg2, arg3] = args;
  3115. const options = {};
  3116. if (!isString(arg1) &&
  3117. !isNumber(arg1) &&
  3118. !isMessageFunction(arg1) &&
  3119. !isMessageAST(arg1)) {
  3120. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3121. }
  3122. // prettier-ignore
  3123. const key = isNumber(arg1)
  3124. ? String(arg1)
  3125. : isMessageFunction(arg1)
  3126. ? arg1
  3127. : arg1;
  3128. if (isNumber(arg2)) {
  3129. options.plural = arg2;
  3130. }
  3131. else if (isString(arg2)) {
  3132. options.default = arg2;
  3133. }
  3134. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  3135. options.named = arg2;
  3136. }
  3137. else if (isArray(arg2)) {
  3138. options.list = arg2;
  3139. }
  3140. if (isNumber(arg3)) {
  3141. options.plural = arg3;
  3142. }
  3143. else if (isString(arg3)) {
  3144. options.default = arg3;
  3145. }
  3146. else if (isPlainObject(arg3)) {
  3147. assign(options, arg3);
  3148. }
  3149. return [key, options];
  3150. }
  3151. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  3152. return {
  3153. locale,
  3154. key,
  3155. warnHtmlMessage,
  3156. onError: (err) => {
  3157. onError && onError(err);
  3158. {
  3159. const _source = getSourceForCodeFrame(source);
  3160. const message = `Message compilation error: ${err.message}`;
  3161. const codeFrame = err.location &&
  3162. _source &&
  3163. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  3164. const emitter = context.__v_emitter;
  3165. if (emitter && _source) {
  3166. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  3167. message: _source,
  3168. error: err.message,
  3169. start: err.location && err.location.start.offset,
  3170. end: err.location && err.location.end.offset,
  3171. groupId: `${'translate'}:${key}`
  3172. });
  3173. }
  3174. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  3175. }
  3176. },
  3177. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  3178. };
  3179. }
  3180. function getSourceForCodeFrame(source) {
  3181. if (isString(source)) {
  3182. return source;
  3183. }
  3184. else {
  3185. if (source.loc && source.loc.source) {
  3186. return source.loc.source;
  3187. }
  3188. }
  3189. }
  3190. function getMessageContextOptions(context, locale, message, options) {
  3191. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  3192. const resolveMessage = (key) => {
  3193. let val = resolveValue(message, key);
  3194. // fallback to root context
  3195. if (val == null && fallbackContext) {
  3196. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  3197. val = resolveValue(message, key);
  3198. }
  3199. if (isString(val) || isMessageAST(val)) {
  3200. let occurred = false;
  3201. const onError = () => {
  3202. occurred = true;
  3203. };
  3204. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  3205. return !occurred
  3206. ? msg
  3207. : NOOP_MESSAGE_FUNCTION;
  3208. }
  3209. else if (isMessageFunction(val)) {
  3210. return val;
  3211. }
  3212. else {
  3213. // TODO: should be implemented warning message
  3214. return NOOP_MESSAGE_FUNCTION;
  3215. }
  3216. };
  3217. const ctxOptions = {
  3218. locale,
  3219. modifiers,
  3220. pluralRules,
  3221. messages: resolveMessage
  3222. };
  3223. if (context.processor) {
  3224. ctxOptions.processor = context.processor;
  3225. }
  3226. if (options.list) {
  3227. ctxOptions.list = options.list;
  3228. }
  3229. if (options.named) {
  3230. ctxOptions.named = options.named;
  3231. }
  3232. if (isNumber(options.plural)) {
  3233. ctxOptions.pluralIndex = options.plural;
  3234. }
  3235. return ctxOptions;
  3236. }
  3237. const intlDefined = typeof Intl !== 'undefined';
  3238. const Availabilities = {
  3239. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  3240. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  3241. };
  3242. // implementation of `datetime` function
  3243. function datetime(context, ...args) {
  3244. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3245. const { __datetimeFormatters } = context;
  3246. if (!Availabilities.dateTimeFormat) {
  3247. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
  3248. return MISSING_RESOLVE_VALUE;
  3249. }
  3250. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  3251. const missingWarn = isBoolean(options.missingWarn)
  3252. ? options.missingWarn
  3253. : context.missingWarn;
  3254. const fallbackWarn = isBoolean(options.fallbackWarn)
  3255. ? options.fallbackWarn
  3256. : context.fallbackWarn;
  3257. const part = !!options.part;
  3258. const locale = getLocale(context, options);
  3259. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3260. fallbackLocale, locale);
  3261. if (!isString(key) || key === '') {
  3262. return new Intl.DateTimeFormat(locale, overrides).format(value);
  3263. }
  3264. // resolve format
  3265. let datetimeFormat = {};
  3266. let targetLocale;
  3267. let format = null;
  3268. let from = locale;
  3269. let to = null;
  3270. const type = 'datetime format';
  3271. for (let i = 0; i < locales.length; i++) {
  3272. targetLocale = to = locales[i];
  3273. if (locale !== targetLocale &&
  3274. isTranslateFallbackWarn(fallbackWarn, key)) {
  3275. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  3276. key,
  3277. target: targetLocale
  3278. }));
  3279. }
  3280. // for vue-devtools timeline event
  3281. if (locale !== targetLocale) {
  3282. const emitter = context.__v_emitter;
  3283. if (emitter) {
  3284. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3285. type,
  3286. key,
  3287. from,
  3288. to,
  3289. groupId: `${type}:${key}`
  3290. });
  3291. }
  3292. }
  3293. datetimeFormat =
  3294. datetimeFormats[targetLocale] || {};
  3295. format = datetimeFormat[key];
  3296. if (isPlainObject(format))
  3297. break;
  3298. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3299. from = to;
  3300. }
  3301. // checking format and target locale
  3302. if (!isPlainObject(format) || !isString(targetLocale)) {
  3303. return unresolving ? NOT_REOSLVED : key;
  3304. }
  3305. let id = `${targetLocale}__${key}`;
  3306. if (!isEmptyObject(overrides)) {
  3307. id = `${id}__${JSON.stringify(overrides)}`;
  3308. }
  3309. let formatter = __datetimeFormatters.get(id);
  3310. if (!formatter) {
  3311. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  3312. __datetimeFormatters.set(id, formatter);
  3313. }
  3314. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3315. }
  3316. /** @internal */
  3317. const DATETIME_FORMAT_OPTIONS_KEYS = [
  3318. 'localeMatcher',
  3319. 'weekday',
  3320. 'era',
  3321. 'year',
  3322. 'month',
  3323. 'day',
  3324. 'hour',
  3325. 'minute',
  3326. 'second',
  3327. 'timeZoneName',
  3328. 'formatMatcher',
  3329. 'hour12',
  3330. 'timeZone',
  3331. 'dateStyle',
  3332. 'timeStyle',
  3333. 'calendar',
  3334. 'dayPeriod',
  3335. 'numberingSystem',
  3336. 'hourCycle',
  3337. 'fractionalSecondDigits'
  3338. ];
  3339. /** @internal */
  3340. function parseDateTimeArgs(...args) {
  3341. const [arg1, arg2, arg3, arg4] = args;
  3342. const options = {};
  3343. let overrides = {};
  3344. let value;
  3345. if (isString(arg1)) {
  3346. // Only allow ISO strings - other date formats are often supported,
  3347. // but may cause different results in different browsers.
  3348. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  3349. if (!matches) {
  3350. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3351. }
  3352. // Some browsers can not parse the iso datetime separated by space,
  3353. // this is a compromise solution by replace the 'T'/' ' with 'T'
  3354. const dateTime = matches[3]
  3355. ? matches[3].trim().startsWith('T')
  3356. ? `${matches[1].trim()}${matches[3].trim()}`
  3357. : `${matches[1].trim()}T${matches[3].trim()}`
  3358. : matches[1].trim();
  3359. value = new Date(dateTime);
  3360. try {
  3361. // This will fail if the date is not valid
  3362. value.toISOString();
  3363. }
  3364. catch (e) {
  3365. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3366. }
  3367. }
  3368. else if (isDate(arg1)) {
  3369. if (isNaN(arg1.getTime())) {
  3370. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  3371. }
  3372. value = arg1;
  3373. }
  3374. else if (isNumber(arg1)) {
  3375. value = arg1;
  3376. }
  3377. else {
  3378. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3379. }
  3380. if (isString(arg2)) {
  3381. options.key = arg2;
  3382. }
  3383. else if (isPlainObject(arg2)) {
  3384. Object.keys(arg2).forEach(key => {
  3385. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  3386. overrides[key] = arg2[key];
  3387. }
  3388. else {
  3389. options[key] = arg2[key];
  3390. }
  3391. });
  3392. }
  3393. if (isString(arg3)) {
  3394. options.locale = arg3;
  3395. }
  3396. else if (isPlainObject(arg3)) {
  3397. overrides = arg3;
  3398. }
  3399. if (isPlainObject(arg4)) {
  3400. overrides = arg4;
  3401. }
  3402. return [options.key || '', value, options, overrides];
  3403. }
  3404. /** @internal */
  3405. function clearDateTimeFormat(ctx, locale, format) {
  3406. const context = ctx;
  3407. for (const key in format) {
  3408. const id = `${locale}__${key}`;
  3409. if (!context.__datetimeFormatters.has(id)) {
  3410. continue;
  3411. }
  3412. context.__datetimeFormatters.delete(id);
  3413. }
  3414. }
  3415. // implementation of `number` function
  3416. function number(context, ...args) {
  3417. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3418. const { __numberFormatters } = context;
  3419. if (!Availabilities.numberFormat) {
  3420. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  3421. return MISSING_RESOLVE_VALUE;
  3422. }
  3423. const [key, value, options, overrides] = parseNumberArgs(...args);
  3424. const missingWarn = isBoolean(options.missingWarn)
  3425. ? options.missingWarn
  3426. : context.missingWarn;
  3427. const fallbackWarn = isBoolean(options.fallbackWarn)
  3428. ? options.fallbackWarn
  3429. : context.fallbackWarn;
  3430. const part = !!options.part;
  3431. const locale = getLocale(context, options);
  3432. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3433. fallbackLocale, locale);
  3434. if (!isString(key) || key === '') {
  3435. return new Intl.NumberFormat(locale, overrides).format(value);
  3436. }
  3437. // resolve format
  3438. let numberFormat = {};
  3439. let targetLocale;
  3440. let format = null;
  3441. let from = locale;
  3442. let to = null;
  3443. const type = 'number format';
  3444. for (let i = 0; i < locales.length; i++) {
  3445. targetLocale = to = locales[i];
  3446. if (locale !== targetLocale &&
  3447. isTranslateFallbackWarn(fallbackWarn, key)) {
  3448. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  3449. key,
  3450. target: targetLocale
  3451. }));
  3452. }
  3453. // for vue-devtools timeline event
  3454. if (locale !== targetLocale) {
  3455. const emitter = context.__v_emitter;
  3456. if (emitter) {
  3457. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3458. type,
  3459. key,
  3460. from,
  3461. to,
  3462. groupId: `${type}:${key}`
  3463. });
  3464. }
  3465. }
  3466. numberFormat =
  3467. numberFormats[targetLocale] || {};
  3468. format = numberFormat[key];
  3469. if (isPlainObject(format))
  3470. break;
  3471. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3472. from = to;
  3473. }
  3474. // checking format and target locale
  3475. if (!isPlainObject(format) || !isString(targetLocale)) {
  3476. return unresolving ? NOT_REOSLVED : key;
  3477. }
  3478. let id = `${targetLocale}__${key}`;
  3479. if (!isEmptyObject(overrides)) {
  3480. id = `${id}__${JSON.stringify(overrides)}`;
  3481. }
  3482. let formatter = __numberFormatters.get(id);
  3483. if (!formatter) {
  3484. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  3485. __numberFormatters.set(id, formatter);
  3486. }
  3487. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3488. }
  3489. /** @internal */
  3490. const NUMBER_FORMAT_OPTIONS_KEYS = [
  3491. 'localeMatcher',
  3492. 'style',
  3493. 'currency',
  3494. 'currencyDisplay',
  3495. 'currencySign',
  3496. 'useGrouping',
  3497. 'minimumIntegerDigits',
  3498. 'minimumFractionDigits',
  3499. 'maximumFractionDigits',
  3500. 'minimumSignificantDigits',
  3501. 'maximumSignificantDigits',
  3502. 'compactDisplay',
  3503. 'notation',
  3504. 'signDisplay',
  3505. 'unit',
  3506. 'unitDisplay',
  3507. 'roundingMode',
  3508. 'roundingPriority',
  3509. 'roundingIncrement',
  3510. 'trailingZeroDisplay'
  3511. ];
  3512. /** @internal */
  3513. function parseNumberArgs(...args) {
  3514. const [arg1, arg2, arg3, arg4] = args;
  3515. const options = {};
  3516. let overrides = {};
  3517. if (!isNumber(arg1)) {
  3518. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3519. }
  3520. const value = arg1;
  3521. if (isString(arg2)) {
  3522. options.key = arg2;
  3523. }
  3524. else if (isPlainObject(arg2)) {
  3525. Object.keys(arg2).forEach(key => {
  3526. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  3527. overrides[key] = arg2[key];
  3528. }
  3529. else {
  3530. options[key] = arg2[key];
  3531. }
  3532. });
  3533. }
  3534. if (isString(arg3)) {
  3535. options.locale = arg3;
  3536. }
  3537. else if (isPlainObject(arg3)) {
  3538. overrides = arg3;
  3539. }
  3540. if (isPlainObject(arg4)) {
  3541. overrides = arg4;
  3542. }
  3543. return [options.key || '', value, options, overrides];
  3544. }
  3545. /** @internal */
  3546. function clearNumberFormat(ctx, locale, format) {
  3547. const context = ctx;
  3548. for (const key in format) {
  3549. const id = `${locale}__${key}`;
  3550. if (!context.__numberFormatters.has(id)) {
  3551. continue;
  3552. }
  3553. context.__numberFormatters.delete(id);
  3554. }
  3555. }
  3556. /**
  3557. * Vue I18n Version
  3558. *
  3559. * @remarks
  3560. * Semver format. Same format as the package.json `version` field.
  3561. *
  3562. * @VueI18nGeneral
  3563. */
  3564. const VERSION = '9.13.1';
  3565. /**
  3566. * This is only called development env
  3567. * istanbul-ignore-next
  3568. */
  3569. function initDev() {
  3570. {
  3571. {
  3572. console.info(`You are running a development build of vue-i18n.\n` +
  3573. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  3574. }
  3575. }
  3576. }
  3577. const code$1 = CoreWarnCodes.__EXTEND_POINT__;
  3578. const inc$1 = incrementer(code$1);
  3579. const I18nWarnCodes = {
  3580. FALLBACK_TO_ROOT: code$1, // 9
  3581. NOT_SUPPORTED_PRESERVE: inc$1(), // 10
  3582. NOT_SUPPORTED_FORMATTER: inc$1(), // 11
  3583. NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(), // 12
  3584. NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(), // 13
  3585. COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(), // 14
  3586. NOT_FOUND_PARENT_SCOPE: inc$1(), // 15
  3587. IGNORE_OBJ_FLATTEN: inc$1(), // 16
  3588. NOTICE_DROP_ALLOW_COMPOSITION: inc$1(), // 17
  3589. NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG: inc$1() // 18
  3590. };
  3591. const warnMessages = {
  3592. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  3593. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
  3594. [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
  3595. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
  3596. [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
  3597. [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  3598. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  3599. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  3600. [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`,
  3601. [I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG]: `'translateExistCompatible' option will be dropped in the next major version.`
  3602. };
  3603. function getWarnMessage(code, ...args) {
  3604. return format$1(warnMessages[code], ...args);
  3605. }
  3606. const code = CoreErrorCodes.__EXTEND_POINT__;
  3607. const inc = incrementer(code);
  3608. const I18nErrorCodes = {
  3609. // composer module errors
  3610. UNEXPECTED_RETURN_TYPE: code, // 24
  3611. // legacy module errors
  3612. INVALID_ARGUMENT: inc(), // 25
  3613. // i18n module errors
  3614. MUST_BE_CALL_SETUP_TOP: inc(), // 26
  3615. NOT_INSTALLED: inc(), // 27
  3616. NOT_AVAILABLE_IN_LEGACY_MODE: inc(), // 28
  3617. // directive module errors
  3618. REQUIRED_VALUE: inc(), // 29
  3619. INVALID_VALUE: inc(), // 30
  3620. // vue-devtools errors
  3621. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(), // 31
  3622. NOT_INSTALLED_WITH_PROVIDE: inc(), // 32
  3623. // unexpected error
  3624. UNEXPECTED_ERROR: inc(), // 33
  3625. // not compatible legacy vue-i18n constructor
  3626. NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(), // 34
  3627. // bridge support vue 2.x only
  3628. BRIDGE_SUPPORT_VUE_2_ONLY: inc(), // 35
  3629. // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``
  3630. MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(), // 36
  3631. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  3632. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(), // 37
  3633. // for enhancement
  3634. __EXTEND_POINT__: inc() // 38
  3635. };
  3636. function createI18nError(code, ...args) {
  3637. return createCompileError(code, null, { messages: errorMessages, args } );
  3638. }
  3639. const errorMessages = {
  3640. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  3641. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  3642. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  3643. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  3644. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  3645. [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
  3646. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  3647. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  3648. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  3649. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  3650. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  3651. [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',
  3652. [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',
  3653. [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'
  3654. };
  3655. const TranslateVNodeSymbol =
  3656. /* #__PURE__*/ makeSymbol('__translateVNode');
  3657. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  3658. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  3659. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  3660. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  3661. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  3662. const InejctWithOptionSymbol =
  3663. /* #__PURE__*/ makeSymbol('__injectWithOption');
  3664. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  3665. const __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';
  3666. /* eslint-disable @typescript-eslint/no-explicit-any */
  3667. /**
  3668. * Transform flat json in obj to normal json in obj
  3669. */
  3670. function handleFlatJson(obj) {
  3671. // check obj
  3672. if (!isObject(obj)) {
  3673. return obj;
  3674. }
  3675. for (const key in obj) {
  3676. // check key
  3677. if (!hasOwn(obj, key)) {
  3678. continue;
  3679. }
  3680. // handle for normal json
  3681. if (!key.includes('.')) {
  3682. // recursive process value if value is also a object
  3683. if (isObject(obj[key])) {
  3684. handleFlatJson(obj[key]);
  3685. }
  3686. }
  3687. // handle for flat json, transform to normal json
  3688. else {
  3689. // go to the last object
  3690. const subKeys = key.split('.');
  3691. const lastIndex = subKeys.length - 1;
  3692. let currentObj = obj;
  3693. let hasStringValue = false;
  3694. for (let i = 0; i < lastIndex; i++) {
  3695. if (!(subKeys[i] in currentObj)) {
  3696. currentObj[subKeys[i]] = {};
  3697. }
  3698. if (!isObject(currentObj[subKeys[i]])) {
  3699. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  3700. key: subKeys[i]
  3701. }));
  3702. hasStringValue = true;
  3703. break;
  3704. }
  3705. currentObj = currentObj[subKeys[i]];
  3706. }
  3707. // update last object value, delete old property
  3708. if (!hasStringValue) {
  3709. currentObj[subKeys[lastIndex]] = obj[key];
  3710. delete obj[key];
  3711. }
  3712. // recursive process value if value is also a object
  3713. if (isObject(currentObj[subKeys[lastIndex]])) {
  3714. handleFlatJson(currentObj[subKeys[lastIndex]]);
  3715. }
  3716. }
  3717. }
  3718. return obj;
  3719. }
  3720. function getLocaleMessages(locale, options) {
  3721. const { messages, __i18n, messageResolver, flatJson } = options;
  3722. // prettier-ignore
  3723. const ret = (isPlainObject(messages)
  3724. ? messages
  3725. : isArray(__i18n)
  3726. ? {}
  3727. : { [locale]: {} });
  3728. // merge locale messages of i18n custom block
  3729. if (isArray(__i18n)) {
  3730. __i18n.forEach(custom => {
  3731. if ('locale' in custom && 'resource' in custom) {
  3732. const { locale, resource } = custom;
  3733. if (locale) {
  3734. ret[locale] = ret[locale] || {};
  3735. deepCopy(resource, ret[locale]);
  3736. }
  3737. else {
  3738. deepCopy(resource, ret);
  3739. }
  3740. }
  3741. else {
  3742. isString(custom) && deepCopy(JSON.parse(custom), ret);
  3743. }
  3744. });
  3745. }
  3746. // handle messages for flat json
  3747. if (messageResolver == null && flatJson) {
  3748. for (const key in ret) {
  3749. if (hasOwn(ret, key)) {
  3750. handleFlatJson(ret[key]);
  3751. }
  3752. }
  3753. }
  3754. return ret;
  3755. }
  3756. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3757. function getComponentOptions(instance) {
  3758. return instance.type ;
  3759. }
  3760. function adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
  3761. ) {
  3762. let messages = isObject(options.messages) ? options.messages : {};
  3763. if ('__i18nGlobal' in componentOptions) {
  3764. messages = getLocaleMessages(gl.locale.value, {
  3765. messages,
  3766. __i18n: componentOptions.__i18nGlobal
  3767. });
  3768. }
  3769. // merge locale messages
  3770. const locales = Object.keys(messages);
  3771. if (locales.length) {
  3772. locales.forEach(locale => {
  3773. gl.mergeLocaleMessage(locale, messages[locale]);
  3774. });
  3775. }
  3776. {
  3777. // merge datetime formats
  3778. if (isObject(options.datetimeFormats)) {
  3779. const locales = Object.keys(options.datetimeFormats);
  3780. if (locales.length) {
  3781. locales.forEach(locale => {
  3782. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  3783. });
  3784. }
  3785. }
  3786. // merge number formats
  3787. if (isObject(options.numberFormats)) {
  3788. const locales = Object.keys(options.numberFormats);
  3789. if (locales.length) {
  3790. locales.forEach(locale => {
  3791. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  3792. });
  3793. }
  3794. }
  3795. }
  3796. }
  3797. function createTextNode(key) {
  3798. return vue.createVNode(vue.Text, null, key, 0)
  3799. ;
  3800. }
  3801. /* eslint-enable @typescript-eslint/no-explicit-any */
  3802. /* eslint-disable @typescript-eslint/no-explicit-any */
  3803. // extend VNode interface
  3804. const DEVTOOLS_META = '__INTLIFY_META__';
  3805. const NOOP_RETURN_ARRAY = () => [];
  3806. const NOOP_RETURN_FALSE = () => false;
  3807. let composerID = 0;
  3808. function defineCoreMissingHandler(missing) {
  3809. return ((ctx, locale, key, type) => {
  3810. return missing(locale, key, vue.getCurrentInstance() || undefined, type);
  3811. });
  3812. }
  3813. // for Intlify DevTools
  3814. /* #__NO_SIDE_EFFECTS__ */
  3815. const getMetaInfo = () => {
  3816. const instance = vue.getCurrentInstance();
  3817. let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
  3818. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  3819. ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
  3820. : null;
  3821. };
  3822. /**
  3823. * Create composer interface factory
  3824. *
  3825. * @internal
  3826. */
  3827. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  3828. function createComposer(options = {}, VueI18nLegacy) {
  3829. const { __root, __injectWithOption } = options;
  3830. const _isGlobal = __root === undefined;
  3831. const flatJson = options.flatJson;
  3832. const _ref = inBrowser ? vue.ref : vue.shallowRef;
  3833. const translateExistCompatible = !!options.translateExistCompatible;
  3834. {
  3835. if (translateExistCompatible && !false) {
  3836. warnOnce(getWarnMessage(I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG));
  3837. }
  3838. }
  3839. let _inheritLocale = isBoolean(options.inheritLocale)
  3840. ? options.inheritLocale
  3841. : true;
  3842. const _locale = _ref(
  3843. // prettier-ignore
  3844. __root && _inheritLocale
  3845. ? __root.locale.value
  3846. : isString(options.locale)
  3847. ? options.locale
  3848. : DEFAULT_LOCALE);
  3849. const _fallbackLocale = _ref(
  3850. // prettier-ignore
  3851. __root && _inheritLocale
  3852. ? __root.fallbackLocale.value
  3853. : isString(options.fallbackLocale) ||
  3854. isArray(options.fallbackLocale) ||
  3855. isPlainObject(options.fallbackLocale) ||
  3856. options.fallbackLocale === false
  3857. ? options.fallbackLocale
  3858. : _locale.value);
  3859. const _messages = _ref(getLocaleMessages(_locale.value, options));
  3860. // prettier-ignore
  3861. const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)
  3862. ? options.datetimeFormats
  3863. : { [_locale.value]: {} })
  3864. ;
  3865. // prettier-ignore
  3866. const _numberFormats = _ref(isPlainObject(options.numberFormats)
  3867. ? options.numberFormats
  3868. : { [_locale.value]: {} })
  3869. ;
  3870. // warning suppress options
  3871. // prettier-ignore
  3872. let _missingWarn = __root
  3873. ? __root.missingWarn
  3874. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  3875. ? options.missingWarn
  3876. : true;
  3877. // prettier-ignore
  3878. let _fallbackWarn = __root
  3879. ? __root.fallbackWarn
  3880. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  3881. ? options.fallbackWarn
  3882. : true;
  3883. // prettier-ignore
  3884. let _fallbackRoot = __root
  3885. ? __root.fallbackRoot
  3886. : isBoolean(options.fallbackRoot)
  3887. ? options.fallbackRoot
  3888. : true;
  3889. // configure fall back to root
  3890. let _fallbackFormat = !!options.fallbackFormat;
  3891. // runtime missing
  3892. let _missing = isFunction(options.missing) ? options.missing : null;
  3893. let _runtimeMissing = isFunction(options.missing)
  3894. ? defineCoreMissingHandler(options.missing)
  3895. : null;
  3896. // postTranslation handler
  3897. let _postTranslation = isFunction(options.postTranslation)
  3898. ? options.postTranslation
  3899. : null;
  3900. // prettier-ignore
  3901. let _warnHtmlMessage = __root
  3902. ? __root.warnHtmlMessage
  3903. : isBoolean(options.warnHtmlMessage)
  3904. ? options.warnHtmlMessage
  3905. : true;
  3906. let _escapeParameter = !!options.escapeParameter;
  3907. // custom linked modifiers
  3908. // prettier-ignore
  3909. const _modifiers = __root
  3910. ? __root.modifiers
  3911. : isPlainObject(options.modifiers)
  3912. ? options.modifiers
  3913. : {};
  3914. // pluralRules
  3915. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  3916. // runtime context
  3917. // eslint-disable-next-line prefer-const
  3918. let _context;
  3919. const getCoreContext = () => {
  3920. _isGlobal && setFallbackContext(null);
  3921. const ctxOptions = {
  3922. version: VERSION,
  3923. locale: _locale.value,
  3924. fallbackLocale: _fallbackLocale.value,
  3925. messages: _messages.value,
  3926. modifiers: _modifiers,
  3927. pluralRules: _pluralRules,
  3928. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  3929. missingWarn: _missingWarn,
  3930. fallbackWarn: _fallbackWarn,
  3931. fallbackFormat: _fallbackFormat,
  3932. unresolving: true,
  3933. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  3934. warnHtmlMessage: _warnHtmlMessage,
  3935. escapeParameter: _escapeParameter,
  3936. messageResolver: options.messageResolver,
  3937. messageCompiler: options.messageCompiler,
  3938. __meta: { framework: 'vue' }
  3939. };
  3940. {
  3941. ctxOptions.datetimeFormats = _datetimeFormats.value;
  3942. ctxOptions.numberFormats = _numberFormats.value;
  3943. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  3944. ? _context.__datetimeFormatters
  3945. : undefined;
  3946. ctxOptions.__numberFormatters = isPlainObject(_context)
  3947. ? _context.__numberFormatters
  3948. : undefined;
  3949. }
  3950. {
  3951. ctxOptions.__v_emitter = isPlainObject(_context)
  3952. ? _context.__v_emitter
  3953. : undefined;
  3954. }
  3955. const ctx = createCoreContext(ctxOptions);
  3956. _isGlobal && setFallbackContext(ctx);
  3957. return ctx;
  3958. };
  3959. _context = getCoreContext();
  3960. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3961. // track reactivity
  3962. function trackReactivityValues() {
  3963. return [
  3964. _locale.value,
  3965. _fallbackLocale.value,
  3966. _messages.value,
  3967. _datetimeFormats.value,
  3968. _numberFormats.value
  3969. ]
  3970. ;
  3971. }
  3972. // locale
  3973. const locale = vue.computed({
  3974. get: () => _locale.value,
  3975. set: val => {
  3976. _locale.value = val;
  3977. _context.locale = _locale.value;
  3978. }
  3979. });
  3980. // fallbackLocale
  3981. const fallbackLocale = vue.computed({
  3982. get: () => _fallbackLocale.value,
  3983. set: val => {
  3984. _fallbackLocale.value = val;
  3985. _context.fallbackLocale = _fallbackLocale.value;
  3986. updateFallbackLocale(_context, _locale.value, val);
  3987. }
  3988. });
  3989. // messages
  3990. const messages = vue.computed(() => _messages.value);
  3991. // datetimeFormats
  3992. const datetimeFormats = /* #__PURE__*/ vue.computed(() => _datetimeFormats.value);
  3993. // numberFormats
  3994. const numberFormats = /* #__PURE__*/ vue.computed(() => _numberFormats.value);
  3995. // getPostTranslationHandler
  3996. function getPostTranslationHandler() {
  3997. return isFunction(_postTranslation) ? _postTranslation : null;
  3998. }
  3999. // setPostTranslationHandler
  4000. function setPostTranslationHandler(handler) {
  4001. _postTranslation = handler;
  4002. _context.postTranslation = handler;
  4003. }
  4004. // getMissingHandler
  4005. function getMissingHandler() {
  4006. return _missing;
  4007. }
  4008. // setMissingHandler
  4009. function setMissingHandler(handler) {
  4010. if (handler !== null) {
  4011. _runtimeMissing = defineCoreMissingHandler(handler);
  4012. }
  4013. _missing = handler;
  4014. _context.missing = _runtimeMissing;
  4015. }
  4016. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  4017. ) {
  4018. return type !== 'translate' || !arg.resolvedMessage;
  4019. }
  4020. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  4021. trackReactivityValues(); // track reactive dependency
  4022. // NOTE: experimental !!
  4023. let ret;
  4024. try {
  4025. if (true || false) {
  4026. setAdditionalMeta(getMetaInfo());
  4027. }
  4028. if (!_isGlobal) {
  4029. _context.fallbackContext = __root
  4030. ? getFallbackContext()
  4031. : undefined;
  4032. }
  4033. ret = fn(_context);
  4034. }
  4035. finally {
  4036. if (!_isGlobal) {
  4037. _context.fallbackContext = undefined;
  4038. }
  4039. }
  4040. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  4041. isNumber(ret) &&
  4042. ret === NOT_REOSLVED) ||
  4043. (warnType === 'translate exists' && !ret) // for `te`
  4044. ) {
  4045. const [key, arg2] = argumentParser();
  4046. if (__root &&
  4047. isString(key) &&
  4048. isResolvedTranslateMessage(warnType, arg2)) {
  4049. if (_fallbackRoot &&
  4050. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  4051. isTranslateMissingWarn(_missingWarn, key))) {
  4052. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  4053. key,
  4054. type: warnType
  4055. }));
  4056. }
  4057. // for vue-devtools timeline event
  4058. {
  4059. const { __v_emitter: emitter } = _context;
  4060. if (emitter && _fallbackRoot) {
  4061. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  4062. type: warnType,
  4063. key,
  4064. to: 'global',
  4065. groupId: `${warnType}:${key}`
  4066. });
  4067. }
  4068. }
  4069. }
  4070. return __root && _fallbackRoot
  4071. ? fallbackSuccess(__root)
  4072. : fallbackFail(key);
  4073. }
  4074. else if (successCondition(ret)) {
  4075. return ret;
  4076. }
  4077. else {
  4078. /* istanbul ignore next */
  4079. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  4080. }
  4081. };
  4082. // t
  4083. function t(...args) {
  4084. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  4085. }
  4086. // rt
  4087. function rt(...args) {
  4088. const [arg1, arg2, arg3] = args;
  4089. if (arg3 && !isObject(arg3)) {
  4090. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4091. }
  4092. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  4093. }
  4094. // d
  4095. function d(...args) {
  4096. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  4097. }
  4098. // n
  4099. function n(...args) {
  4100. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  4101. }
  4102. // for custom processor
  4103. function normalize(values) {
  4104. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  4105. ? createTextNode(String(val))
  4106. : val);
  4107. }
  4108. const interpolate = (val) => val;
  4109. const processor = {
  4110. normalize,
  4111. interpolate,
  4112. type: 'vnode'
  4113. };
  4114. // translateVNode, using for `i18n-t` component
  4115. function translateVNode(...args) {
  4116. return wrapWithDeps(context => {
  4117. let ret;
  4118. const _context = context;
  4119. try {
  4120. _context.processor = processor;
  4121. ret = Reflect.apply(translate, null, [_context, ...args]);
  4122. }
  4123. finally {
  4124. _context.processor = null;
  4125. }
  4126. return ret;
  4127. }, () => parseTranslateArgs(...args), 'translate',
  4128. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4129. root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  4130. }
  4131. // numberParts, using for `i18n-n` component
  4132. function numberParts(...args) {
  4133. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
  4134. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4135. root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4136. }
  4137. // datetimeParts, using for `i18n-d` component
  4138. function datetimeParts(...args) {
  4139. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
  4140. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4141. root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4142. }
  4143. function setPluralRules(rules) {
  4144. _pluralRules = rules;
  4145. _context.pluralRules = _pluralRules;
  4146. }
  4147. // te
  4148. function te(key, locale) {
  4149. return wrapWithDeps(() => {
  4150. if (!key) {
  4151. return false;
  4152. }
  4153. const targetLocale = isString(locale) ? locale : _locale.value;
  4154. const message = getLocaleMessage(targetLocale);
  4155. const resolved = _context.messageResolver(message, key);
  4156. return !translateExistCompatible
  4157. ? isMessageAST(resolved) ||
  4158. isMessageFunction(resolved) ||
  4159. isString(resolved)
  4160. : resolved != null;
  4161. }, () => [key], 'translate exists', root => {
  4162. return Reflect.apply(root.te, root, [key, locale]);
  4163. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  4164. }
  4165. function resolveMessages(key) {
  4166. let messages = null;
  4167. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  4168. for (let i = 0; i < locales.length; i++) {
  4169. const targetLocaleMessages = _messages.value[locales[i]] || {};
  4170. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  4171. if (messageValue != null) {
  4172. messages = messageValue;
  4173. break;
  4174. }
  4175. }
  4176. return messages;
  4177. }
  4178. // tm
  4179. function tm(key) {
  4180. const messages = resolveMessages(key);
  4181. // prettier-ignore
  4182. return messages != null
  4183. ? messages
  4184. : __root
  4185. ? __root.tm(key) || {}
  4186. : {};
  4187. }
  4188. // getLocaleMessage
  4189. function getLocaleMessage(locale) {
  4190. return (_messages.value[locale] || {});
  4191. }
  4192. // setLocaleMessage
  4193. function setLocaleMessage(locale, message) {
  4194. if (flatJson) {
  4195. const _message = { [locale]: message };
  4196. for (const key in _message) {
  4197. if (hasOwn(_message, key)) {
  4198. handleFlatJson(_message[key]);
  4199. }
  4200. }
  4201. message = _message[locale];
  4202. }
  4203. _messages.value[locale] = message;
  4204. _context.messages = _messages.value;
  4205. }
  4206. // mergeLocaleMessage
  4207. function mergeLocaleMessage(locale, message) {
  4208. _messages.value[locale] = _messages.value[locale] || {};
  4209. const _message = { [locale]: message };
  4210. if (flatJson) {
  4211. for (const key in _message) {
  4212. if (hasOwn(_message, key)) {
  4213. handleFlatJson(_message[key]);
  4214. }
  4215. }
  4216. }
  4217. message = _message[locale];
  4218. deepCopy(message, _messages.value[locale]);
  4219. _context.messages = _messages.value;
  4220. }
  4221. // getDateTimeFormat
  4222. function getDateTimeFormat(locale) {
  4223. return _datetimeFormats.value[locale] || {};
  4224. }
  4225. // setDateTimeFormat
  4226. function setDateTimeFormat(locale, format) {
  4227. _datetimeFormats.value[locale] = format;
  4228. _context.datetimeFormats = _datetimeFormats.value;
  4229. clearDateTimeFormat(_context, locale, format);
  4230. }
  4231. // mergeDateTimeFormat
  4232. function mergeDateTimeFormat(locale, format) {
  4233. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  4234. _context.datetimeFormats = _datetimeFormats.value;
  4235. clearDateTimeFormat(_context, locale, format);
  4236. }
  4237. // getNumberFormat
  4238. function getNumberFormat(locale) {
  4239. return _numberFormats.value[locale] || {};
  4240. }
  4241. // setNumberFormat
  4242. function setNumberFormat(locale, format) {
  4243. _numberFormats.value[locale] = format;
  4244. _context.numberFormats = _numberFormats.value;
  4245. clearNumberFormat(_context, locale, format);
  4246. }
  4247. // mergeNumberFormat
  4248. function mergeNumberFormat(locale, format) {
  4249. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  4250. _context.numberFormats = _numberFormats.value;
  4251. clearNumberFormat(_context, locale, format);
  4252. }
  4253. // for debug
  4254. composerID++;
  4255. // watch root locale & fallbackLocale
  4256. if (__root && inBrowser) {
  4257. vue.watch(__root.locale, (val) => {
  4258. if (_inheritLocale) {
  4259. _locale.value = val;
  4260. _context.locale = val;
  4261. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4262. }
  4263. });
  4264. vue.watch(__root.fallbackLocale, (val) => {
  4265. if (_inheritLocale) {
  4266. _fallbackLocale.value = val;
  4267. _context.fallbackLocale = val;
  4268. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4269. }
  4270. });
  4271. }
  4272. // define basic composition API!
  4273. const composer = {
  4274. id: composerID,
  4275. locale,
  4276. fallbackLocale,
  4277. get inheritLocale() {
  4278. return _inheritLocale;
  4279. },
  4280. set inheritLocale(val) {
  4281. _inheritLocale = val;
  4282. if (val && __root) {
  4283. _locale.value = __root.locale.value;
  4284. _fallbackLocale.value = __root.fallbackLocale.value;
  4285. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4286. }
  4287. },
  4288. get availableLocales() {
  4289. return Object.keys(_messages.value).sort();
  4290. },
  4291. messages,
  4292. get modifiers() {
  4293. return _modifiers;
  4294. },
  4295. get pluralRules() {
  4296. return _pluralRules || {};
  4297. },
  4298. get isGlobal() {
  4299. return _isGlobal;
  4300. },
  4301. get missingWarn() {
  4302. return _missingWarn;
  4303. },
  4304. set missingWarn(val) {
  4305. _missingWarn = val;
  4306. _context.missingWarn = _missingWarn;
  4307. },
  4308. get fallbackWarn() {
  4309. return _fallbackWarn;
  4310. },
  4311. set fallbackWarn(val) {
  4312. _fallbackWarn = val;
  4313. _context.fallbackWarn = _fallbackWarn;
  4314. },
  4315. get fallbackRoot() {
  4316. return _fallbackRoot;
  4317. },
  4318. set fallbackRoot(val) {
  4319. _fallbackRoot = val;
  4320. },
  4321. get fallbackFormat() {
  4322. return _fallbackFormat;
  4323. },
  4324. set fallbackFormat(val) {
  4325. _fallbackFormat = val;
  4326. _context.fallbackFormat = _fallbackFormat;
  4327. },
  4328. get warnHtmlMessage() {
  4329. return _warnHtmlMessage;
  4330. },
  4331. set warnHtmlMessage(val) {
  4332. _warnHtmlMessage = val;
  4333. _context.warnHtmlMessage = val;
  4334. },
  4335. get escapeParameter() {
  4336. return _escapeParameter;
  4337. },
  4338. set escapeParameter(val) {
  4339. _escapeParameter = val;
  4340. _context.escapeParameter = val;
  4341. },
  4342. t,
  4343. getLocaleMessage,
  4344. setLocaleMessage,
  4345. mergeLocaleMessage,
  4346. getPostTranslationHandler,
  4347. setPostTranslationHandler,
  4348. getMissingHandler,
  4349. setMissingHandler,
  4350. [SetPluralRulesSymbol]: setPluralRules
  4351. };
  4352. {
  4353. composer.datetimeFormats = datetimeFormats;
  4354. composer.numberFormats = numberFormats;
  4355. composer.rt = rt;
  4356. composer.te = te;
  4357. composer.tm = tm;
  4358. composer.d = d;
  4359. composer.n = n;
  4360. composer.getDateTimeFormat = getDateTimeFormat;
  4361. composer.setDateTimeFormat = setDateTimeFormat;
  4362. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  4363. composer.getNumberFormat = getNumberFormat;
  4364. composer.setNumberFormat = setNumberFormat;
  4365. composer.mergeNumberFormat = mergeNumberFormat;
  4366. composer[InejctWithOptionSymbol] = __injectWithOption;
  4367. composer[TranslateVNodeSymbol] = translateVNode;
  4368. composer[DatetimePartsSymbol] = datetimeParts;
  4369. composer[NumberPartsSymbol] = numberParts;
  4370. }
  4371. // for vue-devtools timeline event
  4372. {
  4373. composer[EnableEmitter] = (emitter) => {
  4374. _context.__v_emitter = emitter;
  4375. };
  4376. composer[DisableEmitter] = () => {
  4377. _context.__v_emitter = undefined;
  4378. };
  4379. }
  4380. return composer;
  4381. }
  4382. /* eslint-enable @typescript-eslint/no-explicit-any */
  4383. /* eslint-disable @typescript-eslint/no-explicit-any */
  4384. /**
  4385. * Convert to I18n Composer Options from VueI18n Options
  4386. *
  4387. * @internal
  4388. */
  4389. function convertComposerOptions(options) {
  4390. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  4391. const fallbackLocale = isString(options.fallbackLocale) ||
  4392. isArray(options.fallbackLocale) ||
  4393. isPlainObject(options.fallbackLocale) ||
  4394. options.fallbackLocale === false
  4395. ? options.fallbackLocale
  4396. : locale;
  4397. const missing = isFunction(options.missing) ? options.missing : undefined;
  4398. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  4399. isRegExp(options.silentTranslationWarn)
  4400. ? !options.silentTranslationWarn
  4401. : true;
  4402. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  4403. isRegExp(options.silentFallbackWarn)
  4404. ? !options.silentFallbackWarn
  4405. : true;
  4406. const fallbackRoot = isBoolean(options.fallbackRoot)
  4407. ? options.fallbackRoot
  4408. : true;
  4409. const fallbackFormat = !!options.formatFallbackMessages;
  4410. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  4411. const pluralizationRules = options.pluralizationRules;
  4412. const postTranslation = isFunction(options.postTranslation)
  4413. ? options.postTranslation
  4414. : undefined;
  4415. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  4416. ? options.warnHtmlInMessage !== 'off'
  4417. : true;
  4418. const escapeParameter = !!options.escapeParameterHtml;
  4419. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  4420. if (options.formatter) {
  4421. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4422. }
  4423. if (options.preserveDirectiveContent) {
  4424. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4425. }
  4426. let messages = options.messages;
  4427. if (isPlainObject(options.sharedMessages)) {
  4428. const sharedMessages = options.sharedMessages;
  4429. const locales = Object.keys(sharedMessages);
  4430. messages = locales.reduce((messages, locale) => {
  4431. const message = messages[locale] || (messages[locale] = {});
  4432. assign(message, sharedMessages[locale]);
  4433. return messages;
  4434. }, (messages || {}));
  4435. }
  4436. const { __i18n, __root, __injectWithOption } = options;
  4437. const datetimeFormats = options.datetimeFormats;
  4438. const numberFormats = options.numberFormats;
  4439. const flatJson = options.flatJson;
  4440. const translateExistCompatible = options
  4441. .translateExistCompatible;
  4442. return {
  4443. locale,
  4444. fallbackLocale,
  4445. messages,
  4446. flatJson,
  4447. datetimeFormats,
  4448. numberFormats,
  4449. missing,
  4450. missingWarn,
  4451. fallbackWarn,
  4452. fallbackRoot,
  4453. fallbackFormat,
  4454. modifiers,
  4455. pluralRules: pluralizationRules,
  4456. postTranslation,
  4457. warnHtmlMessage,
  4458. escapeParameter,
  4459. messageResolver: options.messageResolver,
  4460. inheritLocale,
  4461. translateExistCompatible,
  4462. __i18n,
  4463. __root,
  4464. __injectWithOption
  4465. };
  4466. }
  4467. /**
  4468. * create VueI18n interface factory
  4469. *
  4470. * @internal
  4471. */
  4472. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  4473. function createVueI18n(options = {}, VueI18nLegacy) {
  4474. {
  4475. const composer = createComposer(convertComposerOptions(options));
  4476. const { __extender } = options;
  4477. // defines VueI18n
  4478. const vueI18n = {
  4479. // id
  4480. id: composer.id,
  4481. // locale
  4482. get locale() {
  4483. return composer.locale.value;
  4484. },
  4485. set locale(val) {
  4486. composer.locale.value = val;
  4487. },
  4488. // fallbackLocale
  4489. get fallbackLocale() {
  4490. return composer.fallbackLocale.value;
  4491. },
  4492. set fallbackLocale(val) {
  4493. composer.fallbackLocale.value = val;
  4494. },
  4495. // messages
  4496. get messages() {
  4497. return composer.messages.value;
  4498. },
  4499. // datetimeFormats
  4500. get datetimeFormats() {
  4501. return composer.datetimeFormats.value;
  4502. },
  4503. // numberFormats
  4504. get numberFormats() {
  4505. return composer.numberFormats.value;
  4506. },
  4507. // availableLocales
  4508. get availableLocales() {
  4509. return composer.availableLocales;
  4510. },
  4511. // formatter
  4512. get formatter() {
  4513. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4514. // dummy
  4515. return {
  4516. interpolate() {
  4517. return [];
  4518. }
  4519. };
  4520. },
  4521. set formatter(val) {
  4522. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4523. },
  4524. // missing
  4525. get missing() {
  4526. return composer.getMissingHandler();
  4527. },
  4528. set missing(handler) {
  4529. composer.setMissingHandler(handler);
  4530. },
  4531. // silentTranslationWarn
  4532. get silentTranslationWarn() {
  4533. return isBoolean(composer.missingWarn)
  4534. ? !composer.missingWarn
  4535. : composer.missingWarn;
  4536. },
  4537. set silentTranslationWarn(val) {
  4538. composer.missingWarn = isBoolean(val) ? !val : val;
  4539. },
  4540. // silentFallbackWarn
  4541. get silentFallbackWarn() {
  4542. return isBoolean(composer.fallbackWarn)
  4543. ? !composer.fallbackWarn
  4544. : composer.fallbackWarn;
  4545. },
  4546. set silentFallbackWarn(val) {
  4547. composer.fallbackWarn = isBoolean(val) ? !val : val;
  4548. },
  4549. // modifiers
  4550. get modifiers() {
  4551. return composer.modifiers;
  4552. },
  4553. // formatFallbackMessages
  4554. get formatFallbackMessages() {
  4555. return composer.fallbackFormat;
  4556. },
  4557. set formatFallbackMessages(val) {
  4558. composer.fallbackFormat = val;
  4559. },
  4560. // postTranslation
  4561. get postTranslation() {
  4562. return composer.getPostTranslationHandler();
  4563. },
  4564. set postTranslation(handler) {
  4565. composer.setPostTranslationHandler(handler);
  4566. },
  4567. // sync
  4568. get sync() {
  4569. return composer.inheritLocale;
  4570. },
  4571. set sync(val) {
  4572. composer.inheritLocale = val;
  4573. },
  4574. // warnInHtmlMessage
  4575. get warnHtmlInMessage() {
  4576. return composer.warnHtmlMessage ? 'warn' : 'off';
  4577. },
  4578. set warnHtmlInMessage(val) {
  4579. composer.warnHtmlMessage = val !== 'off';
  4580. },
  4581. // escapeParameterHtml
  4582. get escapeParameterHtml() {
  4583. return composer.escapeParameter;
  4584. },
  4585. set escapeParameterHtml(val) {
  4586. composer.escapeParameter = val;
  4587. },
  4588. // preserveDirectiveContent
  4589. get preserveDirectiveContent() {
  4590. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4591. return true;
  4592. },
  4593. set preserveDirectiveContent(val) {
  4594. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4595. },
  4596. // pluralizationRules
  4597. get pluralizationRules() {
  4598. return composer.pluralRules || {};
  4599. },
  4600. // for internal
  4601. __composer: composer,
  4602. // t
  4603. t(...args) {
  4604. const [arg1, arg2, arg3] = args;
  4605. const options = {};
  4606. let list = null;
  4607. let named = null;
  4608. if (!isString(arg1)) {
  4609. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4610. }
  4611. const key = arg1;
  4612. if (isString(arg2)) {
  4613. options.locale = arg2;
  4614. }
  4615. else if (isArray(arg2)) {
  4616. list = arg2;
  4617. }
  4618. else if (isPlainObject(arg2)) {
  4619. named = arg2;
  4620. }
  4621. if (isArray(arg3)) {
  4622. list = arg3;
  4623. }
  4624. else if (isPlainObject(arg3)) {
  4625. named = arg3;
  4626. }
  4627. // return composer.t(key, (list || named || {}) as any, options)
  4628. return Reflect.apply(composer.t, composer, [
  4629. key,
  4630. (list || named || {}),
  4631. options
  4632. ]);
  4633. },
  4634. rt(...args) {
  4635. return Reflect.apply(composer.rt, composer, [...args]);
  4636. },
  4637. // tc
  4638. tc(...args) {
  4639. const [arg1, arg2, arg3] = args;
  4640. const options = { plural: 1 };
  4641. let list = null;
  4642. let named = null;
  4643. if (!isString(arg1)) {
  4644. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4645. }
  4646. const key = arg1;
  4647. if (isString(arg2)) {
  4648. options.locale = arg2;
  4649. }
  4650. else if (isNumber(arg2)) {
  4651. options.plural = arg2;
  4652. }
  4653. else if (isArray(arg2)) {
  4654. list = arg2;
  4655. }
  4656. else if (isPlainObject(arg2)) {
  4657. named = arg2;
  4658. }
  4659. if (isString(arg3)) {
  4660. options.locale = arg3;
  4661. }
  4662. else if (isArray(arg3)) {
  4663. list = arg3;
  4664. }
  4665. else if (isPlainObject(arg3)) {
  4666. named = arg3;
  4667. }
  4668. // return composer.t(key, (list || named || {}) as any, options)
  4669. return Reflect.apply(composer.t, composer, [
  4670. key,
  4671. (list || named || {}),
  4672. options
  4673. ]);
  4674. },
  4675. // te
  4676. te(key, locale) {
  4677. return composer.te(key, locale);
  4678. },
  4679. // tm
  4680. tm(key) {
  4681. return composer.tm(key);
  4682. },
  4683. // getLocaleMessage
  4684. getLocaleMessage(locale) {
  4685. return composer.getLocaleMessage(locale);
  4686. },
  4687. // setLocaleMessage
  4688. setLocaleMessage(locale, message) {
  4689. composer.setLocaleMessage(locale, message);
  4690. },
  4691. // mergeLocaleMessage
  4692. mergeLocaleMessage(locale, message) {
  4693. composer.mergeLocaleMessage(locale, message);
  4694. },
  4695. // d
  4696. d(...args) {
  4697. return Reflect.apply(composer.d, composer, [...args]);
  4698. },
  4699. // getDateTimeFormat
  4700. getDateTimeFormat(locale) {
  4701. return composer.getDateTimeFormat(locale);
  4702. },
  4703. // setDateTimeFormat
  4704. setDateTimeFormat(locale, format) {
  4705. composer.setDateTimeFormat(locale, format);
  4706. },
  4707. // mergeDateTimeFormat
  4708. mergeDateTimeFormat(locale, format) {
  4709. composer.mergeDateTimeFormat(locale, format);
  4710. },
  4711. // n
  4712. n(...args) {
  4713. return Reflect.apply(composer.n, composer, [...args]);
  4714. },
  4715. // getNumberFormat
  4716. getNumberFormat(locale) {
  4717. return composer.getNumberFormat(locale);
  4718. },
  4719. // setNumberFormat
  4720. setNumberFormat(locale, format) {
  4721. composer.setNumberFormat(locale, format);
  4722. },
  4723. // mergeNumberFormat
  4724. mergeNumberFormat(locale, format) {
  4725. composer.mergeNumberFormat(locale, format);
  4726. },
  4727. // getChoiceIndex
  4728. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  4729. getChoiceIndex(choice, choicesLength) {
  4730. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
  4731. return -1;
  4732. }
  4733. };
  4734. vueI18n.__extender = __extender;
  4735. // for vue-devtools timeline event
  4736. {
  4737. vueI18n.__enableEmitter = (emitter) => {
  4738. const __composer = composer;
  4739. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  4740. };
  4741. vueI18n.__disableEmitter = () => {
  4742. const __composer = composer;
  4743. __composer[DisableEmitter] && __composer[DisableEmitter]();
  4744. };
  4745. }
  4746. return vueI18n;
  4747. }
  4748. }
  4749. /* eslint-enable @typescript-eslint/no-explicit-any */
  4750. const baseFormatProps = {
  4751. tag: {
  4752. type: [String, Object]
  4753. },
  4754. locale: {
  4755. type: String
  4756. },
  4757. scope: {
  4758. type: String,
  4759. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  4760. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  4761. default: 'parent' /* ComponentI18nScope */
  4762. },
  4763. i18n: {
  4764. type: Object
  4765. }
  4766. };
  4767. function getInterpolateArg(
  4768. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4769. { slots }, // SetupContext,
  4770. keys) {
  4771. if (keys.length === 1 && keys[0] === 'default') {
  4772. // default slot with list
  4773. const ret = slots.default ? slots.default() : [];
  4774. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4775. return ret.reduce((slot, current) => {
  4776. return [
  4777. ...slot,
  4778. // prettier-ignore
  4779. ...(current.type === vue.Fragment ? current.children : [current]
  4780. )
  4781. ];
  4782. }, []);
  4783. }
  4784. else {
  4785. // named slots
  4786. return keys.reduce((arg, key) => {
  4787. const slot = slots[key];
  4788. if (slot) {
  4789. arg[key] = slot();
  4790. }
  4791. return arg;
  4792. }, {});
  4793. }
  4794. }
  4795. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4796. function getFragmentableTag(tag) {
  4797. return vue.Fragment ;
  4798. }
  4799. const TranslationImpl = /*#__PURE__*/ vue.defineComponent({
  4800. /* eslint-disable */
  4801. name: 'i18n-t',
  4802. props: assign({
  4803. keypath: {
  4804. type: String,
  4805. required: true
  4806. },
  4807. plural: {
  4808. type: [Number, String],
  4809. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4810. validator: (val) => isNumber(val) || !isNaN(val)
  4811. }
  4812. }, baseFormatProps),
  4813. /* eslint-enable */
  4814. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4815. setup(props, context) {
  4816. const { slots, attrs } = context;
  4817. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  4818. const i18n = props.i18n ||
  4819. useI18n({
  4820. useScope: props.scope,
  4821. __useComponent: true
  4822. });
  4823. return () => {
  4824. const keys = Object.keys(slots).filter(key => key !== '_');
  4825. const options = {};
  4826. if (props.locale) {
  4827. options.locale = props.locale;
  4828. }
  4829. if (props.plural !== undefined) {
  4830. options.plural = isString(props.plural) ? +props.plural : props.plural;
  4831. }
  4832. const arg = getInterpolateArg(context, keys);
  4833. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4834. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  4835. const assignedAttrs = assign({}, attrs);
  4836. const tag = isString(props.tag) || isObject(props.tag)
  4837. ? props.tag
  4838. : getFragmentableTag();
  4839. return vue.h(tag, assignedAttrs, children);
  4840. };
  4841. }
  4842. });
  4843. /**
  4844. * export the public type for h/tsx inference
  4845. * also to avoid inline import() in generated d.ts files
  4846. */
  4847. /**
  4848. * Translation Component
  4849. *
  4850. * @remarks
  4851. * See the following items for property about details
  4852. *
  4853. * @VueI18nSee [TranslationProps](component#translationprops)
  4854. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4855. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  4856. *
  4857. * @example
  4858. * ```html
  4859. * <div id="app">
  4860. * <!-- ... -->
  4861. * <i18n keypath="term" tag="label" for="tos">
  4862. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  4863. * </i18n>
  4864. * <!-- ... -->
  4865. * </div>
  4866. * ```
  4867. * ```js
  4868. * import { createApp } from 'vue'
  4869. * import { createI18n } from 'vue-i18n'
  4870. *
  4871. * const messages = {
  4872. * en: {
  4873. * tos: 'Term of Service',
  4874. * term: 'I accept xxx {0}.'
  4875. * },
  4876. * ja: {
  4877. * tos: '利用規約',
  4878. * term: '私は xxx の{0}に同意します。'
  4879. * }
  4880. * }
  4881. *
  4882. * const i18n = createI18n({
  4883. * locale: 'en',
  4884. * messages
  4885. * })
  4886. *
  4887. * const app = createApp({
  4888. * data: {
  4889. * url: '/term'
  4890. * }
  4891. * }).use(i18n).mount('#app')
  4892. * ```
  4893. *
  4894. * @VueI18nComponent
  4895. */
  4896. const Translation = TranslationImpl;
  4897. const I18nT = Translation;
  4898. function isVNode(target) {
  4899. return isArray(target) && !isString(target[0]);
  4900. }
  4901. function renderFormatter(props, context, slotKeys, partFormatter) {
  4902. const { slots, attrs } = context;
  4903. return () => {
  4904. const options = { part: true };
  4905. let overrides = {};
  4906. if (props.locale) {
  4907. options.locale = props.locale;
  4908. }
  4909. if (isString(props.format)) {
  4910. options.key = props.format;
  4911. }
  4912. else if (isObject(props.format)) {
  4913. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4914. if (isString(props.format.key)) {
  4915. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4916. options.key = props.format.key;
  4917. }
  4918. // Filter out number format options only
  4919. overrides = Object.keys(props.format).reduce((options, prop) => {
  4920. return slotKeys.includes(prop)
  4921. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  4922. : options;
  4923. }, {});
  4924. }
  4925. const parts = partFormatter(...[props.value, options, overrides]);
  4926. let children = [options.key];
  4927. if (isArray(parts)) {
  4928. children = parts.map((part, index) => {
  4929. const slot = slots[part.type];
  4930. const node = slot
  4931. ? slot({ [part.type]: part.value, index, parts })
  4932. : [part.value];
  4933. if (isVNode(node)) {
  4934. node[0].key = `${part.type}-${index}`;
  4935. }
  4936. return node;
  4937. });
  4938. }
  4939. else if (isString(parts)) {
  4940. children = [parts];
  4941. }
  4942. const assignedAttrs = assign({}, attrs);
  4943. const tag = isString(props.tag) || isObject(props.tag)
  4944. ? props.tag
  4945. : getFragmentableTag();
  4946. return vue.h(tag, assignedAttrs, children);
  4947. };
  4948. }
  4949. const NumberFormatImpl = /*#__PURE__*/ vue.defineComponent({
  4950. /* eslint-disable */
  4951. name: 'i18n-n',
  4952. props: assign({
  4953. value: {
  4954. type: Number,
  4955. required: true
  4956. },
  4957. format: {
  4958. type: [String, Object]
  4959. }
  4960. }, baseFormatProps),
  4961. /* eslint-enable */
  4962. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4963. setup(props, context) {
  4964. const i18n = props.i18n ||
  4965. useI18n({
  4966. useScope: props.scope,
  4967. __useComponent: true
  4968. });
  4969. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  4970. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4971. i18n[NumberPartsSymbol](...args));
  4972. }
  4973. });
  4974. /**
  4975. * export the public type for h/tsx inference
  4976. * also to avoid inline import() in generated d.ts files
  4977. */
  4978. /**
  4979. * Number Format Component
  4980. *
  4981. * @remarks
  4982. * See the following items for property about details
  4983. *
  4984. * @VueI18nSee [FormattableProps](component#formattableprops)
  4985. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4986. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  4987. *
  4988. * @VueI18nDanger
  4989. * 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)
  4990. *
  4991. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  4992. *
  4993. * @VueI18nComponent
  4994. */
  4995. const NumberFormat = NumberFormatImpl;
  4996. const I18nN = NumberFormat;
  4997. const DatetimeFormatImpl = /* #__PURE__*/ vue.defineComponent({
  4998. /* eslint-disable */
  4999. name: 'i18n-d',
  5000. props: assign({
  5001. value: {
  5002. type: [Number, Date],
  5003. required: true
  5004. },
  5005. format: {
  5006. type: [String, Object]
  5007. }
  5008. }, baseFormatProps),
  5009. /* eslint-enable */
  5010. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5011. setup(props, context) {
  5012. const i18n = props.i18n ||
  5013. useI18n({
  5014. useScope: props.scope,
  5015. __useComponent: true
  5016. });
  5017. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  5018. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5019. i18n[DatetimePartsSymbol](...args));
  5020. }
  5021. });
  5022. /**
  5023. * Datetime Format Component
  5024. *
  5025. * @remarks
  5026. * See the following items for property about details
  5027. *
  5028. * @VueI18nSee [FormattableProps](component#formattableprops)
  5029. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  5030. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  5031. *
  5032. * @VueI18nDanger
  5033. * 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)
  5034. *
  5035. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  5036. *
  5037. * @VueI18nComponent
  5038. */
  5039. const DatetimeFormat = DatetimeFormatImpl;
  5040. const I18nD = DatetimeFormat;
  5041. function getComposer$2(i18n, instance) {
  5042. const i18nInternal = i18n;
  5043. if (i18n.mode === 'composition') {
  5044. return (i18nInternal.__getInstance(instance) || i18n.global);
  5045. }
  5046. else {
  5047. const vueI18n = i18nInternal.__getInstance(instance);
  5048. return vueI18n != null
  5049. ? vueI18n.__composer
  5050. : i18n.global.__composer;
  5051. }
  5052. }
  5053. function vTDirective(i18n) {
  5054. const _process = (binding) => {
  5055. const { instance, modifiers, value } = binding;
  5056. /* istanbul ignore if */
  5057. if (!instance || !instance.$) {
  5058. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5059. }
  5060. const composer = getComposer$2(i18n, instance.$);
  5061. if (modifiers.preserve) {
  5062. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
  5063. }
  5064. const parsedValue = parseValue(value);
  5065. return [
  5066. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  5067. composer
  5068. ];
  5069. };
  5070. const register = (el, binding) => {
  5071. const [textContent, composer] = _process(binding);
  5072. if (inBrowser && i18n.global === composer) {
  5073. // global scope only
  5074. el.__i18nWatcher = vue.watch(composer.locale, () => {
  5075. binding.instance && binding.instance.$forceUpdate();
  5076. });
  5077. }
  5078. el.__composer = composer;
  5079. el.textContent = textContent;
  5080. };
  5081. const unregister = (el) => {
  5082. if (inBrowser && el.__i18nWatcher) {
  5083. el.__i18nWatcher();
  5084. el.__i18nWatcher = undefined;
  5085. delete el.__i18nWatcher;
  5086. }
  5087. if (el.__composer) {
  5088. el.__composer = undefined;
  5089. delete el.__composer;
  5090. }
  5091. };
  5092. const update = (el, { value }) => {
  5093. if (el.__composer) {
  5094. const composer = el.__composer;
  5095. const parsedValue = parseValue(value);
  5096. el.textContent = Reflect.apply(composer.t, composer, [
  5097. ...makeParams(parsedValue)
  5098. ]);
  5099. }
  5100. };
  5101. const getSSRProps = (binding) => {
  5102. const [textContent] = _process(binding);
  5103. return { textContent };
  5104. };
  5105. return {
  5106. created: register,
  5107. unmounted: unregister,
  5108. beforeUpdate: update,
  5109. getSSRProps
  5110. };
  5111. }
  5112. function parseValue(value) {
  5113. if (isString(value)) {
  5114. return { path: value };
  5115. }
  5116. else if (isPlainObject(value)) {
  5117. if (!('path' in value)) {
  5118. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  5119. }
  5120. return value;
  5121. }
  5122. else {
  5123. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  5124. }
  5125. }
  5126. function makeParams(value) {
  5127. const { path, locale, args, choice, plural } = value;
  5128. const options = {};
  5129. const named = args || {};
  5130. if (isString(locale)) {
  5131. options.locale = locale;
  5132. }
  5133. if (isNumber(choice)) {
  5134. options.plural = choice;
  5135. }
  5136. if (isNumber(plural)) {
  5137. options.plural = plural;
  5138. }
  5139. return [path, named, options];
  5140. }
  5141. function apply(app, i18n, ...options) {
  5142. const pluginOptions = isPlainObject(options[0])
  5143. ? options[0]
  5144. : {};
  5145. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  5146. const globalInstall = isBoolean(pluginOptions.globalInstall)
  5147. ? pluginOptions.globalInstall
  5148. : true;
  5149. if (globalInstall && useI18nComponentName) {
  5150. warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
  5151. name: Translation.name
  5152. }));
  5153. }
  5154. if (globalInstall) {
  5155. [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));
  5156. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  5157. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  5158. }
  5159. // install directive
  5160. {
  5161. app.directive('t', vTDirective(i18n));
  5162. }
  5163. }
  5164. var global$1 = (typeof global !== "undefined" ? global :
  5165. typeof self !== "undefined" ? self :
  5166. typeof window !== "undefined" ? window : {});
  5167. function getDevtoolsGlobalHook() {
  5168. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  5169. }
  5170. function getTarget() {
  5171. // @ts-ignore
  5172. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  5173. ? window
  5174. : typeof global$1 !== 'undefined'
  5175. ? global$1
  5176. : {};
  5177. }
  5178. const isProxyAvailable = typeof Proxy === 'function';
  5179. const HOOK_SETUP = 'devtools-plugin:setup';
  5180. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  5181. let supported;
  5182. let perf;
  5183. function isPerformanceSupported() {
  5184. var _a;
  5185. if (supported !== undefined) {
  5186. return supported;
  5187. }
  5188. if (typeof window !== 'undefined' && window.performance) {
  5189. supported = true;
  5190. perf = window.performance;
  5191. }
  5192. else if (typeof global$1 !== 'undefined' && ((_a = global$1.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  5193. supported = true;
  5194. perf = global$1.perf_hooks.performance;
  5195. }
  5196. else {
  5197. supported = false;
  5198. }
  5199. return supported;
  5200. }
  5201. function now() {
  5202. return isPerformanceSupported() ? perf.now() : Date.now();
  5203. }
  5204. class ApiProxy {
  5205. constructor(plugin, hook) {
  5206. this.target = null;
  5207. this.targetQueue = [];
  5208. this.onQueue = [];
  5209. this.plugin = plugin;
  5210. this.hook = hook;
  5211. const defaultSettings = {};
  5212. if (plugin.settings) {
  5213. for (const id in plugin.settings) {
  5214. const item = plugin.settings[id];
  5215. defaultSettings[id] = item.defaultValue;
  5216. }
  5217. }
  5218. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  5219. let currentSettings = Object.assign({}, defaultSettings);
  5220. try {
  5221. const raw = localStorage.getItem(localSettingsSaveId);
  5222. const data = JSON.parse(raw);
  5223. Object.assign(currentSettings, data);
  5224. }
  5225. catch (e) {
  5226. // noop
  5227. }
  5228. this.fallbacks = {
  5229. getSettings() {
  5230. return currentSettings;
  5231. },
  5232. setSettings(value) {
  5233. try {
  5234. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  5235. }
  5236. catch (e) {
  5237. // noop
  5238. }
  5239. currentSettings = value;
  5240. },
  5241. now() {
  5242. return now();
  5243. },
  5244. };
  5245. if (hook) {
  5246. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  5247. if (pluginId === this.plugin.id) {
  5248. this.fallbacks.setSettings(value);
  5249. }
  5250. });
  5251. }
  5252. this.proxiedOn = new Proxy({}, {
  5253. get: (_target, prop) => {
  5254. if (this.target) {
  5255. return this.target.on[prop];
  5256. }
  5257. else {
  5258. return (...args) => {
  5259. this.onQueue.push({
  5260. method: prop,
  5261. args,
  5262. });
  5263. };
  5264. }
  5265. },
  5266. });
  5267. this.proxiedTarget = new Proxy({}, {
  5268. get: (_target, prop) => {
  5269. if (this.target) {
  5270. return this.target[prop];
  5271. }
  5272. else if (prop === 'on') {
  5273. return this.proxiedOn;
  5274. }
  5275. else if (Object.keys(this.fallbacks).includes(prop)) {
  5276. return (...args) => {
  5277. this.targetQueue.push({
  5278. method: prop,
  5279. args,
  5280. resolve: () => { },
  5281. });
  5282. return this.fallbacks[prop](...args);
  5283. };
  5284. }
  5285. else {
  5286. return (...args) => {
  5287. return new Promise(resolve => {
  5288. this.targetQueue.push({
  5289. method: prop,
  5290. args,
  5291. resolve,
  5292. });
  5293. });
  5294. };
  5295. }
  5296. },
  5297. });
  5298. }
  5299. async setRealTarget(target) {
  5300. this.target = target;
  5301. for (const item of this.onQueue) {
  5302. this.target.on[item.method](...item.args);
  5303. }
  5304. for (const item of this.targetQueue) {
  5305. item.resolve(await this.target[item.method](...item.args));
  5306. }
  5307. }
  5308. }
  5309. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  5310. const descriptor = pluginDescriptor;
  5311. const target = getTarget();
  5312. const hook = getDevtoolsGlobalHook();
  5313. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  5314. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  5315. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  5316. }
  5317. else {
  5318. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  5319. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  5320. list.push({
  5321. pluginDescriptor: descriptor,
  5322. setupFn,
  5323. proxy,
  5324. });
  5325. if (proxy)
  5326. setupFn(proxy.proxiedTarget);
  5327. }
  5328. }
  5329. const VueDevToolsLabels = {
  5330. ["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',
  5331. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',
  5332. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'
  5333. };
  5334. const VueDevToolsPlaceholders = {
  5335. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  5336. };
  5337. const VueDevToolsTimelineColors = {
  5338. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19
  5339. };
  5340. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  5341. let devtoolsApi;
  5342. async function enableDevTools(app, i18n) {
  5343. return new Promise((resolve, reject) => {
  5344. try {
  5345. setupDevtoolsPlugin({
  5346. id: "vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */,
  5347. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */],
  5348. packageName: 'vue-i18n',
  5349. homepage: 'https://vue-i18n.intlify.dev',
  5350. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  5351. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  5352. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  5353. }, api => {
  5354. devtoolsApi = api;
  5355. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  5356. updateComponentTreeTags(componentInstance, treeNode, i18n);
  5357. });
  5358. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  5359. if (componentInstance.vnode.el &&
  5360. componentInstance.vnode.el.__VUE_I18N__ &&
  5361. instanceData) {
  5362. if (i18n.mode === 'legacy') {
  5363. // ignore global scope on legacy mode
  5364. if (componentInstance.vnode.el.__VUE_I18N__ !==
  5365. i18n.global.__composer) {
  5366. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  5367. }
  5368. }
  5369. else {
  5370. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  5371. }
  5372. }
  5373. });
  5374. api.addInspector({
  5375. id: "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,
  5376. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],
  5377. icon: 'language',
  5378. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]
  5379. });
  5380. api.on.getInspectorTree(payload => {
  5381. if (payload.app === app &&
  5382. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5383. registerScope(payload, i18n);
  5384. }
  5385. });
  5386. const roots = new Map();
  5387. api.on.getInspectorState(async (payload) => {
  5388. if (payload.app === app &&
  5389. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5390. api.unhighlightElement();
  5391. inspectScope(payload, i18n);
  5392. if (payload.nodeId === 'global') {
  5393. if (!roots.has(payload.app)) {
  5394. const [root] = await api.getComponentInstances(payload.app);
  5395. roots.set(payload.app, root);
  5396. }
  5397. api.highlightElement(roots.get(payload.app));
  5398. }
  5399. else {
  5400. const instance = getComponentInstance(payload.nodeId, i18n);
  5401. instance && api.highlightElement(instance);
  5402. }
  5403. }
  5404. });
  5405. api.on.editInspectorState(payload => {
  5406. if (payload.app === app &&
  5407. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5408. editScope(payload, i18n);
  5409. }
  5410. });
  5411. api.addTimelineLayer({
  5412. id: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  5413. label: VueDevToolsLabels["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */],
  5414. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]
  5415. });
  5416. resolve(true);
  5417. });
  5418. }
  5419. catch (e) {
  5420. console.error(e);
  5421. reject(false);
  5422. }
  5423. });
  5424. }
  5425. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5426. function getI18nScopeLable(instance) {
  5427. return (instance.type.name ||
  5428. instance.type.displayName ||
  5429. instance.type.__file ||
  5430. 'Anonymous');
  5431. }
  5432. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  5433. treeNode, i18n) {
  5434. // prettier-ignore
  5435. const global = i18n.mode === 'composition'
  5436. ? i18n.global
  5437. : i18n.global.__composer;
  5438. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  5439. // add custom tags local scope only
  5440. if (instance.vnode.el.__VUE_I18N__ !== global) {
  5441. const tag = {
  5442. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  5443. textColor: 0x000000,
  5444. backgroundColor: 0xffcd19
  5445. };
  5446. treeNode.tags.push(tag);
  5447. }
  5448. }
  5449. }
  5450. function inspectComposer(instanceData, composer) {
  5451. const type = VUE_I18N_COMPONENT_TYPES;
  5452. instanceData.state.push({
  5453. type,
  5454. key: 'locale',
  5455. editable: true,
  5456. value: composer.locale.value
  5457. });
  5458. instanceData.state.push({
  5459. type,
  5460. key: 'availableLocales',
  5461. editable: false,
  5462. value: composer.availableLocales
  5463. });
  5464. instanceData.state.push({
  5465. type,
  5466. key: 'fallbackLocale',
  5467. editable: true,
  5468. value: composer.fallbackLocale.value
  5469. });
  5470. instanceData.state.push({
  5471. type,
  5472. key: 'inheritLocale',
  5473. editable: true,
  5474. value: composer.inheritLocale
  5475. });
  5476. instanceData.state.push({
  5477. type,
  5478. key: 'messages',
  5479. editable: false,
  5480. value: getLocaleMessageValue(composer.messages.value)
  5481. });
  5482. {
  5483. instanceData.state.push({
  5484. type,
  5485. key: 'datetimeFormats',
  5486. editable: false,
  5487. value: composer.datetimeFormats.value
  5488. });
  5489. instanceData.state.push({
  5490. type,
  5491. key: 'numberFormats',
  5492. editable: false,
  5493. value: composer.numberFormats.value
  5494. });
  5495. }
  5496. }
  5497. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5498. function getLocaleMessageValue(messages) {
  5499. const value = {};
  5500. Object.keys(messages).forEach((key) => {
  5501. const v = messages[key];
  5502. if (isFunction(v) && 'source' in v) {
  5503. value[key] = getMessageFunctionDetails(v);
  5504. }
  5505. else if (isMessageAST(v) && v.loc && v.loc.source) {
  5506. value[key] = v.loc.source;
  5507. }
  5508. else if (isObject(v)) {
  5509. value[key] = getLocaleMessageValue(v);
  5510. }
  5511. else {
  5512. value[key] = v;
  5513. }
  5514. });
  5515. return value;
  5516. }
  5517. const ESC = {
  5518. '<': '&lt;',
  5519. '>': '&gt;',
  5520. '"': '&quot;',
  5521. '&': '&amp;'
  5522. };
  5523. function escape(s) {
  5524. return s.replace(/[<>"&]/g, escapeChar);
  5525. }
  5526. function escapeChar(a) {
  5527. return ESC[a] || a;
  5528. }
  5529. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5530. function getMessageFunctionDetails(func) {
  5531. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  5532. return {
  5533. _custom: {
  5534. type: 'function',
  5535. display: `<span>ƒ</span> ${argString}`
  5536. }
  5537. };
  5538. }
  5539. function registerScope(payload, i18n) {
  5540. payload.rootNodes.push({
  5541. id: 'global',
  5542. label: 'Global Scope'
  5543. });
  5544. // prettier-ignore
  5545. const global = i18n.mode === 'composition'
  5546. ? i18n.global
  5547. : i18n.global.__composer;
  5548. for (const [keyInstance, instance] of i18n.__instances) {
  5549. // prettier-ignore
  5550. const composer = i18n.mode === 'composition'
  5551. ? instance
  5552. : instance.__composer;
  5553. if (global === composer) {
  5554. continue;
  5555. }
  5556. payload.rootNodes.push({
  5557. id: composer.id.toString(),
  5558. label: `${getI18nScopeLable(keyInstance)} Scope`
  5559. });
  5560. }
  5561. }
  5562. function getComponentInstance(nodeId, i18n) {
  5563. let instance = null;
  5564. if (nodeId !== 'global') {
  5565. for (const [component, composer] of i18n.__instances.entries()) {
  5566. if (composer.id.toString() === nodeId) {
  5567. instance = component;
  5568. break;
  5569. }
  5570. }
  5571. }
  5572. return instance;
  5573. }
  5574. function getComposer$1(nodeId, i18n) {
  5575. if (nodeId === 'global') {
  5576. return i18n.mode === 'composition'
  5577. ? i18n.global
  5578. : i18n.global.__composer;
  5579. }
  5580. else {
  5581. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  5582. if (instance) {
  5583. return i18n.mode === 'composition'
  5584. ? instance
  5585. : instance.__composer;
  5586. }
  5587. else {
  5588. return null;
  5589. }
  5590. }
  5591. }
  5592. function inspectScope(payload, i18n
  5593. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5594. ) {
  5595. const composer = getComposer$1(payload.nodeId, i18n);
  5596. if (composer) {
  5597. // TODO:
  5598. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5599. payload.state = makeScopeInspectState(composer);
  5600. }
  5601. return null;
  5602. }
  5603. function makeScopeInspectState(composer) {
  5604. const state = {};
  5605. const localeType = 'Locale related info';
  5606. const localeStates = [
  5607. {
  5608. type: localeType,
  5609. key: 'locale',
  5610. editable: true,
  5611. value: composer.locale.value
  5612. },
  5613. {
  5614. type: localeType,
  5615. key: 'fallbackLocale',
  5616. editable: true,
  5617. value: composer.fallbackLocale.value
  5618. },
  5619. {
  5620. type: localeType,
  5621. key: 'availableLocales',
  5622. editable: false,
  5623. value: composer.availableLocales
  5624. },
  5625. {
  5626. type: localeType,
  5627. key: 'inheritLocale',
  5628. editable: true,
  5629. value: composer.inheritLocale
  5630. }
  5631. ];
  5632. state[localeType] = localeStates;
  5633. const localeMessagesType = 'Locale messages info';
  5634. const localeMessagesStates = [
  5635. {
  5636. type: localeMessagesType,
  5637. key: 'messages',
  5638. editable: false,
  5639. value: getLocaleMessageValue(composer.messages.value)
  5640. }
  5641. ];
  5642. state[localeMessagesType] = localeMessagesStates;
  5643. {
  5644. const datetimeFormatsType = 'Datetime formats info';
  5645. const datetimeFormatsStates = [
  5646. {
  5647. type: datetimeFormatsType,
  5648. key: 'datetimeFormats',
  5649. editable: false,
  5650. value: composer.datetimeFormats.value
  5651. }
  5652. ];
  5653. state[datetimeFormatsType] = datetimeFormatsStates;
  5654. const numberFormatsType = 'Datetime formats info';
  5655. const numberFormatsStates = [
  5656. {
  5657. type: numberFormatsType,
  5658. key: 'numberFormats',
  5659. editable: false,
  5660. value: composer.numberFormats.value
  5661. }
  5662. ];
  5663. state[numberFormatsType] = numberFormatsStates;
  5664. }
  5665. return state;
  5666. }
  5667. function addTimelineEvent(event, payload) {
  5668. if (devtoolsApi) {
  5669. let groupId;
  5670. if (payload && 'groupId' in payload) {
  5671. groupId = payload.groupId;
  5672. delete payload.groupId;
  5673. }
  5674. devtoolsApi.addTimelineEvent({
  5675. layerId: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  5676. event: {
  5677. title: event,
  5678. groupId,
  5679. time: Date.now(),
  5680. meta: {},
  5681. data: payload || {},
  5682. logType: event === "compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */
  5683. ? 'error'
  5684. : event === "fallback" /* VueDevToolsTimelineEvents.FALBACK */ ||
  5685. event === "missing" /* VueDevToolsTimelineEvents.MISSING */
  5686. ? 'warning'
  5687. : 'default'
  5688. }
  5689. });
  5690. }
  5691. }
  5692. function editScope(payload, i18n) {
  5693. const composer = getComposer$1(payload.nodeId, i18n);
  5694. if (composer) {
  5695. const [field] = payload.path;
  5696. if (field === 'locale' && isString(payload.state.value)) {
  5697. composer.locale.value = payload.state.value;
  5698. }
  5699. else if (field === 'fallbackLocale' &&
  5700. (isString(payload.state.value) ||
  5701. isArray(payload.state.value) ||
  5702. isObject(payload.state.value))) {
  5703. composer.fallbackLocale.value = payload.state.value;
  5704. }
  5705. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  5706. composer.inheritLocale = payload.state.value;
  5707. }
  5708. }
  5709. }
  5710. /**
  5711. * Supports compatibility for legacy vue-i18n APIs
  5712. * This mixin is used when we use vue-i18n@v9.x or later
  5713. */
  5714. function defineMixin(vuei18n, composer, i18n) {
  5715. return {
  5716. beforeCreate() {
  5717. const instance = vue.getCurrentInstance();
  5718. /* istanbul ignore if */
  5719. if (!instance) {
  5720. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5721. }
  5722. const options = this.$options;
  5723. if (options.i18n) {
  5724. const optionsI18n = options.i18n;
  5725. if (options.__i18n) {
  5726. optionsI18n.__i18n = options.__i18n;
  5727. }
  5728. optionsI18n.__root = composer;
  5729. if (this === this.$root) {
  5730. // merge option and gttach global
  5731. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  5732. }
  5733. else {
  5734. optionsI18n.__injectWithOption = true;
  5735. optionsI18n.__extender = i18n.__vueI18nExtend;
  5736. // atttach local VueI18n instance
  5737. this.$i18n = createVueI18n(optionsI18n);
  5738. // extend VueI18n instance
  5739. const _vueI18n = this.$i18n;
  5740. if (_vueI18n.__extender) {
  5741. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5742. }
  5743. }
  5744. }
  5745. else if (options.__i18n) {
  5746. if (this === this.$root) {
  5747. // merge option and gttach global
  5748. this.$i18n = mergeToGlobal(vuei18n, options);
  5749. }
  5750. else {
  5751. // atttach local VueI18n instance
  5752. this.$i18n = createVueI18n({
  5753. __i18n: options.__i18n,
  5754. __injectWithOption: true,
  5755. __extender: i18n.__vueI18nExtend,
  5756. __root: composer
  5757. });
  5758. // extend VueI18n instance
  5759. const _vueI18n = this.$i18n;
  5760. if (_vueI18n.__extender) {
  5761. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5762. }
  5763. }
  5764. }
  5765. else {
  5766. // attach global VueI18n instance
  5767. this.$i18n = vuei18n;
  5768. }
  5769. if (options.__i18nGlobal) {
  5770. adjustI18nResources(composer, options, options);
  5771. }
  5772. // defines vue-i18n legacy APIs
  5773. this.$t = (...args) => this.$i18n.t(...args);
  5774. this.$rt = (...args) => this.$i18n.rt(...args);
  5775. this.$tc = (...args) => this.$i18n.tc(...args);
  5776. this.$te = (key, locale) => this.$i18n.te(key, locale);
  5777. this.$d = (...args) => this.$i18n.d(...args);
  5778. this.$n = (...args) => this.$i18n.n(...args);
  5779. this.$tm = (key) => this.$i18n.tm(key);
  5780. i18n.__setInstance(instance, this.$i18n);
  5781. },
  5782. mounted() {
  5783. /* istanbul ignore if */
  5784. if (this.$el &&
  5785. this.$i18n) {
  5786. const _vueI18n = this.$i18n;
  5787. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  5788. const emitter = (this.__v_emitter =
  5789. createEmitter());
  5790. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5791. emitter.on('*', addTimelineEvent);
  5792. }
  5793. },
  5794. unmounted() {
  5795. const instance = vue.getCurrentInstance();
  5796. /* istanbul ignore if */
  5797. if (!instance) {
  5798. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5799. }
  5800. const _vueI18n = this.$i18n;
  5801. /* istanbul ignore if */
  5802. if (this.$el &&
  5803. this.$el.__VUE_I18N__) {
  5804. if (this.__v_emitter) {
  5805. this.__v_emitter.off('*', addTimelineEvent);
  5806. delete this.__v_emitter;
  5807. }
  5808. if (this.$i18n) {
  5809. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  5810. delete this.$el.__VUE_I18N__;
  5811. }
  5812. }
  5813. delete this.$t;
  5814. delete this.$rt;
  5815. delete this.$tc;
  5816. delete this.$te;
  5817. delete this.$d;
  5818. delete this.$n;
  5819. delete this.$tm;
  5820. if (_vueI18n.__disposer) {
  5821. _vueI18n.__disposer();
  5822. delete _vueI18n.__disposer;
  5823. delete _vueI18n.__extender;
  5824. }
  5825. i18n.__deleteInstance(instance);
  5826. delete this.$i18n;
  5827. }
  5828. };
  5829. }
  5830. function mergeToGlobal(g, options) {
  5831. g.locale = options.locale || g.locale;
  5832. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  5833. g.missing = options.missing || g.missing;
  5834. g.silentTranslationWarn =
  5835. options.silentTranslationWarn || g.silentFallbackWarn;
  5836. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  5837. g.formatFallbackMessages =
  5838. options.formatFallbackMessages || g.formatFallbackMessages;
  5839. g.postTranslation = options.postTranslation || g.postTranslation;
  5840. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  5841. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  5842. g.sync = options.sync || g.sync;
  5843. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  5844. const messages = getLocaleMessages(g.locale, {
  5845. messages: options.messages,
  5846. __i18n: options.__i18n
  5847. });
  5848. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  5849. if (options.datetimeFormats) {
  5850. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  5851. }
  5852. if (options.numberFormats) {
  5853. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  5854. }
  5855. return g;
  5856. }
  5857. /**
  5858. * Injection key for {@link useI18n}
  5859. *
  5860. * @remarks
  5861. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  5862. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  5863. *
  5864. * @VueI18nGeneral
  5865. */
  5866. const I18nInjectionKey =
  5867. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  5868. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  5869. function createI18n(options = {}, VueI18nLegacy) {
  5870. // prettier-ignore
  5871. const __legacyMode = isBoolean(options.legacy)
  5872. ? options.legacy
  5873. : true;
  5874. // prettier-ignore
  5875. const __globalInjection = isBoolean(options.globalInjection)
  5876. ? options.globalInjection
  5877. : true;
  5878. // prettier-ignore
  5879. const __allowComposition = __legacyMode
  5880. ? !!options.allowComposition
  5881. : true;
  5882. const __instances = new Map();
  5883. const [globalScope, __global] = createGlobal(options, __legacyMode);
  5884. const symbol = /* #__PURE__*/ makeSymbol('vue-i18n' );
  5885. {
  5886. if (__legacyMode && __allowComposition && !false) {
  5887. warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));
  5888. }
  5889. }
  5890. function __getInstance(component) {
  5891. return __instances.get(component) || null;
  5892. }
  5893. function __setInstance(component, instance) {
  5894. __instances.set(component, instance);
  5895. }
  5896. function __deleteInstance(component) {
  5897. __instances.delete(component);
  5898. }
  5899. {
  5900. const i18n = {
  5901. // mode
  5902. get mode() {
  5903. return __legacyMode
  5904. ? 'legacy'
  5905. : 'composition';
  5906. },
  5907. // allowComposition
  5908. get allowComposition() {
  5909. return __allowComposition;
  5910. },
  5911. // install plugin
  5912. async install(app, ...options) {
  5913. {
  5914. app.__VUE_I18N__ = i18n;
  5915. }
  5916. // setup global provider
  5917. app.__VUE_I18N_SYMBOL__ = symbol;
  5918. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  5919. // set composer & vuei18n extend hook options from plugin options
  5920. if (isPlainObject(options[0])) {
  5921. const opts = options[0];
  5922. i18n.__composerExtend =
  5923. opts.__composerExtend;
  5924. i18n.__vueI18nExtend =
  5925. opts.__vueI18nExtend;
  5926. }
  5927. // global method and properties injection for Composition API
  5928. let globalReleaseHandler = null;
  5929. if (!__legacyMode && __globalInjection) {
  5930. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  5931. }
  5932. // install built-in components and directive
  5933. {
  5934. apply(app, i18n, ...options);
  5935. }
  5936. // setup mixin for Legacy API
  5937. if (__legacyMode) {
  5938. app.mixin(defineMixin(__global, __global.__composer, i18n));
  5939. }
  5940. // release global scope
  5941. const unmountApp = app.unmount;
  5942. app.unmount = () => {
  5943. globalReleaseHandler && globalReleaseHandler();
  5944. i18n.dispose();
  5945. unmountApp();
  5946. };
  5947. // setup vue-devtools plugin
  5948. {
  5949. const ret = await enableDevTools(app, i18n);
  5950. if (!ret) {
  5951. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  5952. }
  5953. const emitter = createEmitter();
  5954. if (__legacyMode) {
  5955. const _vueI18n = __global;
  5956. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5957. }
  5958. else {
  5959. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5960. const _composer = __global;
  5961. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  5962. }
  5963. emitter.on('*', addTimelineEvent);
  5964. }
  5965. },
  5966. // global accessor
  5967. get global() {
  5968. return __global;
  5969. },
  5970. dispose() {
  5971. globalScope.stop();
  5972. },
  5973. // @internal
  5974. __instances,
  5975. // @internal
  5976. __getInstance,
  5977. // @internal
  5978. __setInstance,
  5979. // @internal
  5980. __deleteInstance
  5981. };
  5982. return i18n;
  5983. }
  5984. }
  5985. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  5986. function useI18n(options = {}) {
  5987. const instance = vue.getCurrentInstance();
  5988. if (instance == null) {
  5989. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  5990. }
  5991. if (!instance.isCE &&
  5992. instance.appContext.app != null &&
  5993. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  5994. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  5995. }
  5996. const i18n = getI18nInstance(instance);
  5997. const gl = getGlobalComposer(i18n);
  5998. const componentOptions = getComponentOptions(instance);
  5999. const scope = getScope(options, componentOptions);
  6000. {
  6001. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6002. if (i18n.mode === 'legacy' && !options.__useComponent) {
  6003. if (!i18n.allowComposition) {
  6004. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
  6005. }
  6006. return useI18nForLegacy(instance, scope, gl, options);
  6007. }
  6008. }
  6009. if (scope === 'global') {
  6010. adjustI18nResources(gl, options, componentOptions);
  6011. return gl;
  6012. }
  6013. if (scope === 'parent') {
  6014. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6015. let composer = getComposer(i18n, instance, options.__useComponent);
  6016. if (composer == null) {
  6017. {
  6018. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  6019. }
  6020. composer = gl;
  6021. }
  6022. return composer;
  6023. }
  6024. const i18nInternal = i18n;
  6025. let composer = i18nInternal.__getInstance(instance);
  6026. if (composer == null) {
  6027. const composerOptions = assign({}, options);
  6028. if ('__i18n' in componentOptions) {
  6029. composerOptions.__i18n = componentOptions.__i18n;
  6030. }
  6031. if (gl) {
  6032. composerOptions.__root = gl;
  6033. }
  6034. composer = createComposer(composerOptions);
  6035. if (i18nInternal.__composerExtend) {
  6036. composer[DisposeSymbol] =
  6037. i18nInternal.__composerExtend(composer);
  6038. }
  6039. setupLifeCycle(i18nInternal, instance, composer);
  6040. i18nInternal.__setInstance(instance, composer);
  6041. }
  6042. return composer;
  6043. }
  6044. /**
  6045. * Cast to VueI18n legacy compatible type
  6046. *
  6047. * @remarks
  6048. * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
  6049. *
  6050. * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.
  6051. *
  6052. * @param i18n - An instance of {@link I18n}
  6053. * @returns A i18n instance which is casted to {@link VueI18n} type
  6054. *
  6055. * @VueI18nTip
  6056. * :new: provided by **vue-i18n-bridge only**
  6057. *
  6058. * @VueI18nGeneral
  6059. */
  6060. /* #__NO_SIDE_EFFECTS__ */
  6061. const castToVueI18n = (i18n
  6062. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6063. ) => {
  6064. if (!(__VUE_I18N_BRIDGE__ in i18n)) {
  6065. throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
  6066. }
  6067. return i18n;
  6068. };
  6069. function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
  6070. ) {
  6071. const scope = vue.effectScope();
  6072. {
  6073. const obj = legacyMode
  6074. ? scope.run(() => createVueI18n(options))
  6075. : scope.run(() => createComposer(options));
  6076. if (obj == null) {
  6077. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6078. }
  6079. return [scope, obj];
  6080. }
  6081. }
  6082. function getI18nInstance(instance) {
  6083. {
  6084. const i18n = vue.inject(!instance.isCE
  6085. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  6086. : I18nInjectionKey);
  6087. /* istanbul ignore if */
  6088. if (!i18n) {
  6089. throw createI18nError(!instance.isCE
  6090. ? I18nErrorCodes.UNEXPECTED_ERROR
  6091. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  6092. }
  6093. return i18n;
  6094. }
  6095. }
  6096. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6097. function getScope(options, componentOptions) {
  6098. // prettier-ignore
  6099. return isEmptyObject(options)
  6100. ? ('__i18n' in componentOptions)
  6101. ? 'local'
  6102. : 'global'
  6103. : !options.useScope
  6104. ? 'local'
  6105. : options.useScope;
  6106. }
  6107. function getGlobalComposer(i18n) {
  6108. // prettier-ignore
  6109. return i18n.mode === 'composition'
  6110. ? i18n.global
  6111. : i18n.global.__composer
  6112. ;
  6113. }
  6114. function getComposer(i18n, target, useComponent = false) {
  6115. let composer = null;
  6116. const root = target.root;
  6117. let current = getParentComponentInstance(target, useComponent);
  6118. while (current != null) {
  6119. const i18nInternal = i18n;
  6120. if (i18n.mode === 'composition') {
  6121. composer = i18nInternal.__getInstance(current);
  6122. }
  6123. else {
  6124. {
  6125. const vueI18n = i18nInternal.__getInstance(current);
  6126. if (vueI18n != null) {
  6127. composer = vueI18n
  6128. .__composer;
  6129. if (useComponent &&
  6130. composer &&
  6131. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  6132. ) {
  6133. composer = null;
  6134. }
  6135. }
  6136. }
  6137. }
  6138. if (composer != null) {
  6139. break;
  6140. }
  6141. if (root === current) {
  6142. break;
  6143. }
  6144. current = current.parent;
  6145. }
  6146. return composer;
  6147. }
  6148. function getParentComponentInstance(target, useComponent = false) {
  6149. if (target == null) {
  6150. return null;
  6151. }
  6152. {
  6153. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  6154. return !useComponent
  6155. ? target.parent
  6156. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  6157. }
  6158. }
  6159. function setupLifeCycle(i18n, target, composer) {
  6160. let emitter = null;
  6161. {
  6162. vue.onMounted(() => {
  6163. // inject composer instance to DOM for intlify-devtools
  6164. if (target.vnode.el) {
  6165. target.vnode.el.__VUE_I18N__ = composer;
  6166. emitter = createEmitter();
  6167. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6168. const _composer = composer;
  6169. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  6170. emitter.on('*', addTimelineEvent);
  6171. }
  6172. }, target);
  6173. vue.onUnmounted(() => {
  6174. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6175. const _composer = composer;
  6176. // remove composer instance from DOM for intlify-devtools
  6177. if (target.vnode.el &&
  6178. target.vnode.el.__VUE_I18N__) {
  6179. emitter && emitter.off('*', addTimelineEvent);
  6180. _composer[DisableEmitter] && _composer[DisableEmitter]();
  6181. delete target.vnode.el.__VUE_I18N__;
  6182. }
  6183. i18n.__deleteInstance(target);
  6184. // dispose extended resources
  6185. const dispose = _composer[DisposeSymbol];
  6186. if (dispose) {
  6187. dispose();
  6188. delete _composer[DisposeSymbol];
  6189. }
  6190. }, target);
  6191. }
  6192. }
  6193. function useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any
  6194. ) {
  6195. const isLocalScope = scope === 'local';
  6196. const _composer = vue.shallowRef(null);
  6197. if (isLocalScope &&
  6198. instance.proxy &&
  6199. !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {
  6200. throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);
  6201. }
  6202. const _inheritLocale = isBoolean(options.inheritLocale)
  6203. ? options.inheritLocale
  6204. : !isString(options.locale);
  6205. const _locale = vue.ref(
  6206. // prettier-ignore
  6207. !isLocalScope || _inheritLocale
  6208. ? root.locale.value
  6209. : isString(options.locale)
  6210. ? options.locale
  6211. : DEFAULT_LOCALE);
  6212. const _fallbackLocale = vue.ref(
  6213. // prettier-ignore
  6214. !isLocalScope || _inheritLocale
  6215. ? root.fallbackLocale.value
  6216. : isString(options.fallbackLocale) ||
  6217. isArray(options.fallbackLocale) ||
  6218. isPlainObject(options.fallbackLocale) ||
  6219. options.fallbackLocale === false
  6220. ? options.fallbackLocale
  6221. : _locale.value);
  6222. const _messages = vue.ref(getLocaleMessages(_locale.value, options));
  6223. // prettier-ignore
  6224. const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats)
  6225. ? options.datetimeFormats
  6226. : { [_locale.value]: {} });
  6227. // prettier-ignore
  6228. const _numberFormats = vue.ref(isPlainObject(options.numberFormats)
  6229. ? options.numberFormats
  6230. : { [_locale.value]: {} });
  6231. // prettier-ignore
  6232. const _missingWarn = isLocalScope
  6233. ? root.missingWarn
  6234. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  6235. ? options.missingWarn
  6236. : true;
  6237. // prettier-ignore
  6238. const _fallbackWarn = isLocalScope
  6239. ? root.fallbackWarn
  6240. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  6241. ? options.fallbackWarn
  6242. : true;
  6243. // prettier-ignore
  6244. const _fallbackRoot = isLocalScope
  6245. ? root.fallbackRoot
  6246. : isBoolean(options.fallbackRoot)
  6247. ? options.fallbackRoot
  6248. : true;
  6249. // configure fall back to root
  6250. const _fallbackFormat = !!options.fallbackFormat;
  6251. // runtime missing
  6252. const _missing = isFunction(options.missing) ? options.missing : null;
  6253. // postTranslation handler
  6254. const _postTranslation = isFunction(options.postTranslation)
  6255. ? options.postTranslation
  6256. : null;
  6257. // prettier-ignore
  6258. const _warnHtmlMessage = isLocalScope
  6259. ? root.warnHtmlMessage
  6260. : isBoolean(options.warnHtmlMessage)
  6261. ? options.warnHtmlMessage
  6262. : true;
  6263. const _escapeParameter = !!options.escapeParameter;
  6264. // prettier-ignore
  6265. const _modifiers = isLocalScope
  6266. ? root.modifiers
  6267. : isPlainObject(options.modifiers)
  6268. ? options.modifiers
  6269. : {};
  6270. // pluralRules
  6271. const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);
  6272. // track reactivity
  6273. function trackReactivityValues() {
  6274. return [
  6275. _locale.value,
  6276. _fallbackLocale.value,
  6277. _messages.value,
  6278. _datetimeFormats.value,
  6279. _numberFormats.value
  6280. ];
  6281. }
  6282. // locale
  6283. const locale = vue.computed({
  6284. get: () => {
  6285. return _composer.value ? _composer.value.locale.value : _locale.value;
  6286. },
  6287. set: val => {
  6288. if (_composer.value) {
  6289. _composer.value.locale.value = val;
  6290. }
  6291. _locale.value = val;
  6292. }
  6293. });
  6294. // fallbackLocale
  6295. const fallbackLocale = vue.computed({
  6296. get: () => {
  6297. return _composer.value
  6298. ? _composer.value.fallbackLocale.value
  6299. : _fallbackLocale.value;
  6300. },
  6301. set: val => {
  6302. if (_composer.value) {
  6303. _composer.value.fallbackLocale.value = val;
  6304. }
  6305. _fallbackLocale.value = val;
  6306. }
  6307. });
  6308. // messages
  6309. const messages = vue.computed(() => {
  6310. if (_composer.value) {
  6311. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6312. return _composer.value.messages.value;
  6313. }
  6314. else {
  6315. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6316. return _messages.value;
  6317. }
  6318. });
  6319. const datetimeFormats = vue.computed(() => _datetimeFormats.value);
  6320. const numberFormats = vue.computed(() => _numberFormats.value);
  6321. function getPostTranslationHandler() {
  6322. return _composer.value
  6323. ? _composer.value.getPostTranslationHandler()
  6324. : _postTranslation;
  6325. }
  6326. function setPostTranslationHandler(handler) {
  6327. if (_composer.value) {
  6328. _composer.value.setPostTranslationHandler(handler);
  6329. }
  6330. }
  6331. function getMissingHandler() {
  6332. return _composer.value ? _composer.value.getMissingHandler() : _missing;
  6333. }
  6334. function setMissingHandler(handler) {
  6335. if (_composer.value) {
  6336. _composer.value.setMissingHandler(handler);
  6337. }
  6338. }
  6339. function warpWithDeps(fn) {
  6340. trackReactivityValues();
  6341. return fn();
  6342. }
  6343. function t(...args) {
  6344. return _composer.value
  6345. ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))
  6346. : warpWithDeps(() => '');
  6347. }
  6348. function rt(...args) {
  6349. return _composer.value
  6350. ? Reflect.apply(_composer.value.rt, null, [...args])
  6351. : '';
  6352. }
  6353. function d(...args) {
  6354. return _composer.value
  6355. ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))
  6356. : warpWithDeps(() => '');
  6357. }
  6358. function n(...args) {
  6359. return _composer.value
  6360. ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))
  6361. : warpWithDeps(() => '');
  6362. }
  6363. function tm(key) {
  6364. return _composer.value ? _composer.value.tm(key) : {};
  6365. }
  6366. function te(key, locale) {
  6367. return _composer.value ? _composer.value.te(key, locale) : false;
  6368. }
  6369. function getLocaleMessage(locale) {
  6370. return _composer.value ? _composer.value.getLocaleMessage(locale) : {};
  6371. }
  6372. function setLocaleMessage(locale, message) {
  6373. if (_composer.value) {
  6374. _composer.value.setLocaleMessage(locale, message);
  6375. _messages.value[locale] = message;
  6376. }
  6377. }
  6378. function mergeLocaleMessage(locale, message) {
  6379. if (_composer.value) {
  6380. _composer.value.mergeLocaleMessage(locale, message);
  6381. }
  6382. }
  6383. function getDateTimeFormat(locale) {
  6384. return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};
  6385. }
  6386. function setDateTimeFormat(locale, format) {
  6387. if (_composer.value) {
  6388. _composer.value.setDateTimeFormat(locale, format);
  6389. _datetimeFormats.value[locale] = format;
  6390. }
  6391. }
  6392. function mergeDateTimeFormat(locale, format) {
  6393. if (_composer.value) {
  6394. _composer.value.mergeDateTimeFormat(locale, format);
  6395. }
  6396. }
  6397. function getNumberFormat(locale) {
  6398. return _composer.value ? _composer.value.getNumberFormat(locale) : {};
  6399. }
  6400. function setNumberFormat(locale, format) {
  6401. if (_composer.value) {
  6402. _composer.value.setNumberFormat(locale, format);
  6403. _numberFormats.value[locale] = format;
  6404. }
  6405. }
  6406. function mergeNumberFormat(locale, format) {
  6407. if (_composer.value) {
  6408. _composer.value.mergeNumberFormat(locale, format);
  6409. }
  6410. }
  6411. const wrapper = {
  6412. get id() {
  6413. return _composer.value ? _composer.value.id : -1;
  6414. },
  6415. locale,
  6416. fallbackLocale,
  6417. messages,
  6418. datetimeFormats,
  6419. numberFormats,
  6420. get inheritLocale() {
  6421. return _composer.value ? _composer.value.inheritLocale : _inheritLocale;
  6422. },
  6423. set inheritLocale(val) {
  6424. if (_composer.value) {
  6425. _composer.value.inheritLocale = val;
  6426. }
  6427. },
  6428. get availableLocales() {
  6429. return _composer.value
  6430. ? _composer.value.availableLocales
  6431. : Object.keys(_messages.value);
  6432. },
  6433. get modifiers() {
  6434. return (_composer.value ? _composer.value.modifiers : _modifiers);
  6435. },
  6436. get pluralRules() {
  6437. return (_composer.value ? _composer.value.pluralRules : _pluralRules);
  6438. },
  6439. get isGlobal() {
  6440. return _composer.value ? _composer.value.isGlobal : false;
  6441. },
  6442. get missingWarn() {
  6443. return _composer.value ? _composer.value.missingWarn : _missingWarn;
  6444. },
  6445. set missingWarn(val) {
  6446. if (_composer.value) {
  6447. _composer.value.missingWarn = val;
  6448. }
  6449. },
  6450. get fallbackWarn() {
  6451. return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;
  6452. },
  6453. set fallbackWarn(val) {
  6454. if (_composer.value) {
  6455. _composer.value.missingWarn = val;
  6456. }
  6457. },
  6458. get fallbackRoot() {
  6459. return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;
  6460. },
  6461. set fallbackRoot(val) {
  6462. if (_composer.value) {
  6463. _composer.value.fallbackRoot = val;
  6464. }
  6465. },
  6466. get fallbackFormat() {
  6467. return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;
  6468. },
  6469. set fallbackFormat(val) {
  6470. if (_composer.value) {
  6471. _composer.value.fallbackFormat = val;
  6472. }
  6473. },
  6474. get warnHtmlMessage() {
  6475. return _composer.value
  6476. ? _composer.value.warnHtmlMessage
  6477. : _warnHtmlMessage;
  6478. },
  6479. set warnHtmlMessage(val) {
  6480. if (_composer.value) {
  6481. _composer.value.warnHtmlMessage = val;
  6482. }
  6483. },
  6484. get escapeParameter() {
  6485. return _composer.value
  6486. ? _composer.value.escapeParameter
  6487. : _escapeParameter;
  6488. },
  6489. set escapeParameter(val) {
  6490. if (_composer.value) {
  6491. _composer.value.escapeParameter = val;
  6492. }
  6493. },
  6494. t,
  6495. getPostTranslationHandler,
  6496. setPostTranslationHandler,
  6497. getMissingHandler,
  6498. setMissingHandler,
  6499. rt,
  6500. d,
  6501. n,
  6502. tm,
  6503. te,
  6504. getLocaleMessage,
  6505. setLocaleMessage,
  6506. mergeLocaleMessage,
  6507. getDateTimeFormat,
  6508. setDateTimeFormat,
  6509. mergeDateTimeFormat,
  6510. getNumberFormat,
  6511. setNumberFormat,
  6512. mergeNumberFormat
  6513. };
  6514. function sync(composer) {
  6515. composer.locale.value = _locale.value;
  6516. composer.fallbackLocale.value = _fallbackLocale.value;
  6517. Object.keys(_messages.value).forEach(locale => {
  6518. composer.mergeLocaleMessage(locale, _messages.value[locale]);
  6519. });
  6520. Object.keys(_datetimeFormats.value).forEach(locale => {
  6521. composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);
  6522. });
  6523. Object.keys(_numberFormats.value).forEach(locale => {
  6524. composer.mergeNumberFormat(locale, _numberFormats.value[locale]);
  6525. });
  6526. composer.escapeParameter = _escapeParameter;
  6527. composer.fallbackFormat = _fallbackFormat;
  6528. composer.fallbackRoot = _fallbackRoot;
  6529. composer.fallbackWarn = _fallbackWarn;
  6530. composer.missingWarn = _missingWarn;
  6531. composer.warnHtmlMessage = _warnHtmlMessage;
  6532. }
  6533. vue.onBeforeMount(() => {
  6534. if (instance.proxy == null || instance.proxy.$i18n == null) {
  6535. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);
  6536. }
  6537. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6538. const composer = (_composer.value = instance.proxy.$i18n
  6539. .__composer);
  6540. if (scope === 'global') {
  6541. _locale.value = composer.locale.value;
  6542. _fallbackLocale.value = composer.fallbackLocale.value;
  6543. _messages.value = composer.messages.value;
  6544. _datetimeFormats.value = composer.datetimeFormats.value;
  6545. _numberFormats.value = composer.numberFormats.value;
  6546. }
  6547. else if (isLocalScope) {
  6548. sync(composer);
  6549. }
  6550. });
  6551. return wrapper;
  6552. }
  6553. const globalExportProps = [
  6554. 'locale',
  6555. 'fallbackLocale',
  6556. 'availableLocales'
  6557. ];
  6558. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  6559. ;
  6560. function injectGlobalFields(app, composer) {
  6561. const i18n = Object.create(null);
  6562. globalExportProps.forEach(prop => {
  6563. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  6564. if (!desc) {
  6565. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6566. }
  6567. const wrap = vue.isRef(desc.value) // check computed props
  6568. ? {
  6569. get() {
  6570. return desc.value.value;
  6571. },
  6572. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6573. set(val) {
  6574. desc.value.value = val;
  6575. }
  6576. }
  6577. : {
  6578. get() {
  6579. return desc.get && desc.get();
  6580. }
  6581. };
  6582. Object.defineProperty(i18n, prop, wrap);
  6583. });
  6584. app.config.globalProperties.$i18n = i18n;
  6585. globalExportMethods.forEach(method => {
  6586. const desc = Object.getOwnPropertyDescriptor(composer, method);
  6587. if (!desc || !desc.value) {
  6588. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6589. }
  6590. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  6591. });
  6592. const dispose = () => {
  6593. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6594. delete app.config.globalProperties.$i18n;
  6595. globalExportMethods.forEach(method => {
  6596. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6597. delete app.config.globalProperties[`$${method}`];
  6598. });
  6599. };
  6600. return dispose;
  6601. }
  6602. // register message compiler at vue-i18n
  6603. {
  6604. registerMessageCompiler(compile);
  6605. }
  6606. // register message resolver at vue-i18n
  6607. registerMessageResolver(resolveValue);
  6608. // register fallback locale at vue-i18n
  6609. registerLocaleFallbacker(fallbackWithLocaleChain);
  6610. // NOTE: experimental !!
  6611. {
  6612. const target = getGlobalThis();
  6613. target.__INTLIFY__ = true;
  6614. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  6615. }
  6616. {
  6617. initDev();
  6618. }
  6619. exports.DatetimeFormat = DatetimeFormat;
  6620. exports.I18nD = I18nD;
  6621. exports.I18nInjectionKey = I18nInjectionKey;
  6622. exports.I18nN = I18nN;
  6623. exports.I18nT = I18nT;
  6624. exports.NumberFormat = NumberFormat;
  6625. exports.Translation = Translation;
  6626. exports.VERSION = VERSION;
  6627. exports.castToVueI18n = castToVueI18n;
  6628. exports.createI18n = createI18n;
  6629. exports.useI18n = useI18n;
  6630. exports.vTDirective = vTDirective;
  6631. return exports;
  6632. })({}, Vue);