vue-i18n.esm-browser.js 231 KB

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