b75a4b20cfa2906595526bb67beac216d8a9e9afc8d088cfefeabb1c3ea285f67cb54ece56b812be063d1f08db9f8d0c4eba37d14286881d6aab0a50e3fbdb 237 KB

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