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

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