vue-i18n.runtime.esm-browser.js 170 KB

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