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

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