vue-i18n.runtime.global.js 182 KB

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