vue-i18n.esm-browser.js 208 KB

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