d3a09350c097e1088e6451fca355126076b9408a3f456774e332e38b4590368a14f6106c85d2849960be29b5bd4f9e5b4f6332c2cf0b3dc925ad32263b69d8 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730
  1. /*!
  2. * core-base v9.14.5
  3. * (c) 2025 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. var IntlifyCoreBase = (function (exports) {
  7. 'use strict';
  8. function warn(msg, err) {
  9. if (typeof console !== 'undefined') {
  10. console.warn(`[intlify] ` + msg);
  11. /* istanbul ignore if */
  12. if (err) {
  13. console.warn(err.stack);
  14. }
  15. }
  16. }
  17. /**
  18. * Original Utilities
  19. * written by kazuya kawaguchi
  20. */
  21. const inBrowser = typeof window !== 'undefined';
  22. let mark;
  23. let measure;
  24. {
  25. const perf = inBrowser && window.performance;
  26. if (perf &&
  27. perf.mark &&
  28. perf.measure &&
  29. perf.clearMarks &&
  30. // @ts-ignore browser compat
  31. perf.clearMeasures) {
  32. mark = (tag) => {
  33. perf.mark(tag);
  34. };
  35. measure = (name, startTag, endTag) => {
  36. perf.measure(name, startTag, endTag);
  37. perf.clearMarks(startTag);
  38. perf.clearMarks(endTag);
  39. };
  40. }
  41. }
  42. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  43. /* eslint-disable */
  44. function format$1(message, ...args) {
  45. if (args.length === 1 && isObject(args[0])) {
  46. args = args[0];
  47. }
  48. if (!args || !args.hasOwnProperty) {
  49. args = {};
  50. }
  51. return message.replace(RE_ARGS, (match, identifier) => {
  52. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  53. });
  54. }
  55. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  56. const friendlyJSONstringify = (json) => JSON.stringify(json)
  57. .replace(/\u2028/g, '\\u2028')
  58. .replace(/\u2029/g, '\\u2029')
  59. .replace(/\u0027/g, '\\u0027');
  60. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  61. const isDate = (val) => toTypeString(val) === '[object Date]';
  62. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  63. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  64. const assign = Object.assign;
  65. const _create = Object.create;
  66. const create = (obj = null) => _create(obj);
  67. function escapeHtml(rawText) {
  68. return rawText
  69. .replace(/&/g, '&') // escape `&` first to avoid double escaping
  70. .replace(/</g, '&lt;')
  71. .replace(/>/g, '&gt;')
  72. .replace(/"/g, '&quot;')
  73. .replace(/'/g, '&apos;')
  74. .replace(/\//g, '&#x2F;') // escape `/` to prevent closing tags or JavaScript URLs
  75. .replace(/=/g, '&#x3D;'); // escape `=` to prevent attribute injection
  76. }
  77. function escapeAttributeValue(value) {
  78. return value
  79. .replace(/&(?![a-zA-Z0-9#]{2,6};)/g, '&amp;') // escape unescaped `&`
  80. .replace(/"/g, '&quot;')
  81. .replace(/'/g, '&apos;')
  82. .replace(/</g, '&lt;')
  83. .replace(/>/g, '&gt;');
  84. }
  85. function sanitizeTranslatedHtml(html) {
  86. // Escape dangerous characters in attribute values
  87. // Process attributes with double quotes
  88. html = html.replace(/(\w+)\s*=\s*"([^"]*)"/g, (_, attrName, attrValue) => `${attrName}="${escapeAttributeValue(attrValue)}"`);
  89. // Process attributes with single quotes
  90. html = html.replace(/(\w+)\s*=\s*'([^']*)'/g, (_, attrName, attrValue) => `${attrName}='${escapeAttributeValue(attrValue)}'`);
  91. // Detect and neutralize event handler attributes
  92. const eventHandlerPattern = /\s*on\w+\s*=\s*["']?[^"'>]+["']?/gi;
  93. if (eventHandlerPattern.test(html)) {
  94. {
  95. warn('Potentially dangerous event handlers detected in translation. ' +
  96. 'Consider removing onclick, onerror, etc. from your translation messages.');
  97. }
  98. // Neutralize event handler attributes by escaping 'on'
  99. html = html.replace(/(\s+)(on)(\w+\s*=)/gi, '$1&#111;n$3');
  100. }
  101. // Disable javascript: URLs in various contexts
  102. const javascriptUrlPattern = [
  103. // In href, src, action, formaction attributes
  104. /(\s+(?:href|src|action|formaction)\s*=\s*["']?)\s*javascript:/gi,
  105. // In style attributes within url()
  106. /(style\s*=\s*["'][^"']*url\s*\(\s*)javascript:/gi
  107. ];
  108. javascriptUrlPattern.forEach(pattern => {
  109. html = html.replace(pattern, '$1javascript&#58;');
  110. });
  111. return html;
  112. }
  113. const hasOwnProperty = Object.prototype.hasOwnProperty;
  114. function hasOwn(obj, key) {
  115. return hasOwnProperty.call(obj, key);
  116. }
  117. /* eslint-enable */
  118. /**
  119. * Useful Utilities By Evan you
  120. * Modified by kazuya kawaguchi
  121. * MIT License
  122. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  123. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  124. */
  125. const isArray = Array.isArray;
  126. const isFunction = (val) => typeof val === 'function';
  127. const isString = (val) => typeof val === 'string';
  128. const isBoolean = (val) => typeof val === 'boolean';
  129. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  130. const isObject = (val) => val !== null && typeof val === 'object';
  131. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  132. const isPromise = (val) => {
  133. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  134. };
  135. const objectToString = Object.prototype.toString;
  136. const toTypeString = (value) => objectToString.call(value);
  137. const isPlainObject = (val) => {
  138. if (!isObject(val))
  139. return false;
  140. const proto = Object.getPrototypeOf(val);
  141. return proto === null || proto.constructor === Object;
  142. };
  143. // for converting list and named values to displayed strings.
  144. const toDisplayString = (val) => {
  145. return val == null
  146. ? ''
  147. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  148. ? JSON.stringify(val, null, 2)
  149. : String(val);
  150. };
  151. function join(items, separator = '') {
  152. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  153. }
  154. const RANGE = 2;
  155. function generateCodeFrame(source, start = 0, end = source.length) {
  156. const lines = source.split(/\r?\n/);
  157. let count = 0;
  158. const res = [];
  159. for (let i = 0; i < lines.length; i++) {
  160. count += lines[i].length + 1;
  161. if (count >= start) {
  162. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  163. if (j < 0 || j >= lines.length)
  164. continue;
  165. const line = j + 1;
  166. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  167. const lineLength = lines[j].length;
  168. if (j === i) {
  169. // push underline
  170. const pad = start - (count - lineLength) + 1;
  171. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  172. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  173. }
  174. else if (j > i) {
  175. if (end > count) {
  176. const length = Math.max(Math.min(end - count, lineLength), 1);
  177. res.push(` | ` + '^'.repeat(length));
  178. }
  179. count += lineLength + 1;
  180. }
  181. }
  182. break;
  183. }
  184. }
  185. return res.join('\n');
  186. }
  187. function incrementer(code) {
  188. let current = code;
  189. return () => ++current;
  190. }
  191. function createPosition(line, column, offset) {
  192. return { line, column, offset };
  193. }
  194. function createLocation(start, end, source) {
  195. const loc = { start, end };
  196. if (source != null) {
  197. loc.source = source;
  198. }
  199. return loc;
  200. }
  201. const CompileWarnCodes = {
  202. USE_MODULO_SYNTAX: 1,
  203. __EXTEND_POINT__: 2
  204. };
  205. /** @internal */
  206. const warnMessages$1 = {
  207. [CompileWarnCodes.USE_MODULO_SYNTAX]: `Use modulo before '{{0}}'.`
  208. };
  209. function createCompileWarn(code, loc, ...args) {
  210. const msg = format$1(warnMessages$1[code] || '', ...(args || [])) ;
  211. const message = { message: String(msg), code };
  212. if (loc) {
  213. message.location = loc;
  214. }
  215. return message;
  216. }
  217. const CompileErrorCodes = {
  218. // tokenizer error codes
  219. EXPECTED_TOKEN: 1,
  220. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  221. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  222. UNKNOWN_ESCAPE_SEQUENCE: 4,
  223. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  224. UNBALANCED_CLOSING_BRACE: 6,
  225. UNTERMINATED_CLOSING_BRACE: 7,
  226. EMPTY_PLACEHOLDER: 8,
  227. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  228. INVALID_LINKED_FORMAT: 10,
  229. // parser error codes
  230. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  231. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  232. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  233. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  234. // generator error codes
  235. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  236. // minifier error codes
  237. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  238. // Special value for higher-order compilers to pick up the last code
  239. // to avoid collision of error codes. This should always be kept as the last
  240. // item.
  241. __EXTEND_POINT__: 17
  242. };
  243. /** @internal */
  244. const errorMessages$1 = {
  245. // tokenizer error messages
  246. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  247. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  248. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  249. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  250. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  251. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  252. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  253. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  254. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  255. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  256. // parser error messages
  257. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  258. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  259. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  260. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  261. // generator error messages
  262. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  263. // minimizer error messages
  264. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  265. };
  266. function createCompileError(code, loc, options = {}) {
  267. const { domain, messages, args } = options;
  268. const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
  269. ;
  270. const error = new SyntaxError(String(msg));
  271. error.code = code;
  272. if (loc) {
  273. error.location = loc;
  274. }
  275. error.domain = domain;
  276. return error;
  277. }
  278. /** @internal */
  279. function defaultOnError(error) {
  280. throw error;
  281. }
  282. // eslint-disable-next-line no-useless-escape
  283. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  284. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  285. const CHAR_SP = ' ';
  286. const CHAR_CR = '\r';
  287. const CHAR_LF = '\n';
  288. const CHAR_LS = String.fromCharCode(0x2028);
  289. const CHAR_PS = String.fromCharCode(0x2029);
  290. function createScanner(str) {
  291. const _buf = str;
  292. let _index = 0;
  293. let _line = 1;
  294. let _column = 1;
  295. let _peekOffset = 0;
  296. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  297. const isLF = (index) => _buf[index] === CHAR_LF;
  298. const isPS = (index) => _buf[index] === CHAR_PS;
  299. const isLS = (index) => _buf[index] === CHAR_LS;
  300. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  301. const index = () => _index;
  302. const line = () => _line;
  303. const column = () => _column;
  304. const peekOffset = () => _peekOffset;
  305. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  306. const currentChar = () => charAt(_index);
  307. const currentPeek = () => charAt(_index + _peekOffset);
  308. function next() {
  309. _peekOffset = 0;
  310. if (isLineEnd(_index)) {
  311. _line++;
  312. _column = 0;
  313. }
  314. if (isCRLF(_index)) {
  315. _index++;
  316. }
  317. _index++;
  318. _column++;
  319. return _buf[_index];
  320. }
  321. function peek() {
  322. if (isCRLF(_index + _peekOffset)) {
  323. _peekOffset++;
  324. }
  325. _peekOffset++;
  326. return _buf[_index + _peekOffset];
  327. }
  328. function reset() {
  329. _index = 0;
  330. _line = 1;
  331. _column = 1;
  332. _peekOffset = 0;
  333. }
  334. function resetPeek(offset = 0) {
  335. _peekOffset = offset;
  336. }
  337. function skipToPeek() {
  338. const target = _index + _peekOffset;
  339. // eslint-disable-next-line no-unmodified-loop-condition
  340. while (target !== _index) {
  341. next();
  342. }
  343. _peekOffset = 0;
  344. }
  345. return {
  346. index,
  347. line,
  348. column,
  349. peekOffset,
  350. charAt,
  351. currentChar,
  352. currentPeek,
  353. next,
  354. peek,
  355. reset,
  356. resetPeek,
  357. skipToPeek
  358. };
  359. }
  360. const EOF = undefined;
  361. const DOT = '.';
  362. const LITERAL_DELIMITER = "'";
  363. const ERROR_DOMAIN$3 = 'tokenizer';
  364. function createTokenizer(source, options = {}) {
  365. const location = options.location !== false;
  366. const _scnr = createScanner(source);
  367. const currentOffset = () => _scnr.index();
  368. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  369. const _initLoc = currentPosition();
  370. const _initOffset = currentOffset();
  371. const _context = {
  372. currentType: 14 /* TokenTypes.EOF */,
  373. offset: _initOffset,
  374. startLoc: _initLoc,
  375. endLoc: _initLoc,
  376. lastType: 14 /* TokenTypes.EOF */,
  377. lastOffset: _initOffset,
  378. lastStartLoc: _initLoc,
  379. lastEndLoc: _initLoc,
  380. braceNest: 0,
  381. inLinked: false,
  382. text: ''
  383. };
  384. const context = () => _context;
  385. const { onError } = options;
  386. function emitError(code, pos, offset, ...args) {
  387. const ctx = context();
  388. pos.column += offset;
  389. pos.offset += offset;
  390. if (onError) {
  391. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  392. const err = createCompileError(code, loc, {
  393. domain: ERROR_DOMAIN$3,
  394. args
  395. });
  396. onError(err);
  397. }
  398. }
  399. function getToken(context, type, value) {
  400. context.endLoc = currentPosition();
  401. context.currentType = type;
  402. const token = { type };
  403. if (location) {
  404. token.loc = createLocation(context.startLoc, context.endLoc);
  405. }
  406. if (value != null) {
  407. token.value = value;
  408. }
  409. return token;
  410. }
  411. const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
  412. function eat(scnr, ch) {
  413. if (scnr.currentChar() === ch) {
  414. scnr.next();
  415. return ch;
  416. }
  417. else {
  418. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  419. return '';
  420. }
  421. }
  422. function peekSpaces(scnr) {
  423. let buf = '';
  424. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  425. buf += scnr.currentPeek();
  426. scnr.peek();
  427. }
  428. return buf;
  429. }
  430. function skipSpaces(scnr) {
  431. const buf = peekSpaces(scnr);
  432. scnr.skipToPeek();
  433. return buf;
  434. }
  435. function isIdentifierStart(ch) {
  436. if (ch === EOF) {
  437. return false;
  438. }
  439. const cc = ch.charCodeAt(0);
  440. return ((cc >= 97 && cc <= 122) || // a-z
  441. (cc >= 65 && cc <= 90) || // A-Z
  442. cc === 95 // _
  443. );
  444. }
  445. function isNumberStart(ch) {
  446. if (ch === EOF) {
  447. return false;
  448. }
  449. const cc = ch.charCodeAt(0);
  450. return cc >= 48 && cc <= 57; // 0-9
  451. }
  452. function isNamedIdentifierStart(scnr, context) {
  453. const { currentType } = context;
  454. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  455. return false;
  456. }
  457. peekSpaces(scnr);
  458. const ret = isIdentifierStart(scnr.currentPeek());
  459. scnr.resetPeek();
  460. return ret;
  461. }
  462. function isListIdentifierStart(scnr, context) {
  463. const { currentType } = context;
  464. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  465. return false;
  466. }
  467. peekSpaces(scnr);
  468. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  469. const ret = isNumberStart(ch);
  470. scnr.resetPeek();
  471. return ret;
  472. }
  473. function isLiteralStart(scnr, context) {
  474. const { currentType } = context;
  475. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  476. return false;
  477. }
  478. peekSpaces(scnr);
  479. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  480. scnr.resetPeek();
  481. return ret;
  482. }
  483. function isLinkedDotStart(scnr, context) {
  484. const { currentType } = context;
  485. if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
  486. return false;
  487. }
  488. peekSpaces(scnr);
  489. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  490. scnr.resetPeek();
  491. return ret;
  492. }
  493. function isLinkedModifierStart(scnr, context) {
  494. const { currentType } = context;
  495. if (currentType !== 9 /* TokenTypes.LinkedDot */) {
  496. return false;
  497. }
  498. peekSpaces(scnr);
  499. const ret = isIdentifierStart(scnr.currentPeek());
  500. scnr.resetPeek();
  501. return ret;
  502. }
  503. function isLinkedDelimiterStart(scnr, context) {
  504. const { currentType } = context;
  505. if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
  506. currentType === 12 /* TokenTypes.LinkedModifier */)) {
  507. return false;
  508. }
  509. peekSpaces(scnr);
  510. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  511. scnr.resetPeek();
  512. return ret;
  513. }
  514. function isLinkedReferStart(scnr, context) {
  515. const { currentType } = context;
  516. if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
  517. return false;
  518. }
  519. const fn = () => {
  520. const ch = scnr.currentPeek();
  521. if (ch === "{" /* TokenChars.BraceLeft */) {
  522. return isIdentifierStart(scnr.peek());
  523. }
  524. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  525. ch === "%" /* TokenChars.Modulo */ ||
  526. ch === "|" /* TokenChars.Pipe */ ||
  527. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  528. ch === "." /* TokenChars.LinkedDot */ ||
  529. ch === CHAR_SP ||
  530. !ch) {
  531. return false;
  532. }
  533. else if (ch === CHAR_LF) {
  534. scnr.peek();
  535. return fn();
  536. }
  537. else {
  538. // other characters
  539. return isTextStart(scnr, false);
  540. }
  541. };
  542. const ret = fn();
  543. scnr.resetPeek();
  544. return ret;
  545. }
  546. function isPluralStart(scnr) {
  547. peekSpaces(scnr);
  548. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  549. scnr.resetPeek();
  550. return ret;
  551. }
  552. function detectModuloStart(scnr) {
  553. const spaces = peekSpaces(scnr);
  554. const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
  555. scnr.peek() === "{" /* TokenChars.BraceLeft */;
  556. scnr.resetPeek();
  557. return {
  558. isModulo: ret,
  559. hasSpace: spaces.length > 0
  560. };
  561. }
  562. function isTextStart(scnr, reset = true) {
  563. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  564. const ch = scnr.currentPeek();
  565. if (ch === "{" /* TokenChars.BraceLeft */) {
  566. return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
  567. }
  568. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  569. return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
  570. }
  571. else if (ch === "%" /* TokenChars.Modulo */) {
  572. scnr.peek();
  573. return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
  574. }
  575. else if (ch === "|" /* TokenChars.Pipe */) {
  576. return prev === "%" /* TokenChars.Modulo */ || detectModulo
  577. ? true
  578. : !(prev === CHAR_SP || prev === CHAR_LF);
  579. }
  580. else if (ch === CHAR_SP) {
  581. scnr.peek();
  582. return fn(true, CHAR_SP, detectModulo);
  583. }
  584. else if (ch === CHAR_LF) {
  585. scnr.peek();
  586. return fn(true, CHAR_LF, detectModulo);
  587. }
  588. else {
  589. return true;
  590. }
  591. };
  592. const ret = fn();
  593. reset && scnr.resetPeek();
  594. return ret;
  595. }
  596. function takeChar(scnr, fn) {
  597. const ch = scnr.currentChar();
  598. if (ch === EOF) {
  599. return EOF;
  600. }
  601. if (fn(ch)) {
  602. scnr.next();
  603. return ch;
  604. }
  605. return null;
  606. }
  607. function isIdentifier(ch) {
  608. const cc = ch.charCodeAt(0);
  609. return ((cc >= 97 && cc <= 122) || // a-z
  610. (cc >= 65 && cc <= 90) || // A-Z
  611. (cc >= 48 && cc <= 57) || // 0-9
  612. cc === 95 || // _
  613. cc === 36 // $
  614. );
  615. }
  616. function takeIdentifierChar(scnr) {
  617. return takeChar(scnr, isIdentifier);
  618. }
  619. function isNamedIdentifier(ch) {
  620. const cc = ch.charCodeAt(0);
  621. return ((cc >= 97 && cc <= 122) || // a-z
  622. (cc >= 65 && cc <= 90) || // A-Z
  623. (cc >= 48 && cc <= 57) || // 0-9
  624. cc === 95 || // _
  625. cc === 36 || // $
  626. cc === 45 // -
  627. );
  628. }
  629. function takeNamedIdentifierChar(scnr) {
  630. return takeChar(scnr, isNamedIdentifier);
  631. }
  632. function isDigit(ch) {
  633. const cc = ch.charCodeAt(0);
  634. return cc >= 48 && cc <= 57; // 0-9
  635. }
  636. function takeDigit(scnr) {
  637. return takeChar(scnr, isDigit);
  638. }
  639. function isHexDigit(ch) {
  640. const cc = ch.charCodeAt(0);
  641. return ((cc >= 48 && cc <= 57) || // 0-9
  642. (cc >= 65 && cc <= 70) || // A-F
  643. (cc >= 97 && cc <= 102)); // a-f
  644. }
  645. function takeHexDigit(scnr) {
  646. return takeChar(scnr, isHexDigit);
  647. }
  648. function getDigits(scnr) {
  649. let ch = '';
  650. let num = '';
  651. while ((ch = takeDigit(scnr))) {
  652. num += ch;
  653. }
  654. return num;
  655. }
  656. function readModulo(scnr) {
  657. skipSpaces(scnr);
  658. const ch = scnr.currentChar();
  659. if (ch !== "%" /* TokenChars.Modulo */) {
  660. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  661. }
  662. scnr.next();
  663. return "%" /* TokenChars.Modulo */;
  664. }
  665. function readText(scnr) {
  666. let buf = '';
  667. // eslint-disable-next-line no-constant-condition
  668. while (true) {
  669. const ch = scnr.currentChar();
  670. if (ch === "{" /* TokenChars.BraceLeft */ ||
  671. ch === "}" /* TokenChars.BraceRight */ ||
  672. ch === "@" /* TokenChars.LinkedAlias */ ||
  673. ch === "|" /* TokenChars.Pipe */ ||
  674. !ch) {
  675. break;
  676. }
  677. else if (ch === "%" /* TokenChars.Modulo */) {
  678. if (isTextStart(scnr)) {
  679. buf += ch;
  680. scnr.next();
  681. }
  682. else {
  683. break;
  684. }
  685. }
  686. else if (ch === CHAR_SP || ch === CHAR_LF) {
  687. if (isTextStart(scnr)) {
  688. buf += ch;
  689. scnr.next();
  690. }
  691. else if (isPluralStart(scnr)) {
  692. break;
  693. }
  694. else {
  695. buf += ch;
  696. scnr.next();
  697. }
  698. }
  699. else {
  700. buf += ch;
  701. scnr.next();
  702. }
  703. }
  704. return buf;
  705. }
  706. function readNamedIdentifier(scnr) {
  707. skipSpaces(scnr);
  708. let ch = '';
  709. let name = '';
  710. while ((ch = takeNamedIdentifierChar(scnr))) {
  711. name += ch;
  712. }
  713. if (scnr.currentChar() === EOF) {
  714. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  715. }
  716. return name;
  717. }
  718. function readListIdentifier(scnr) {
  719. skipSpaces(scnr);
  720. let value = '';
  721. if (scnr.currentChar() === '-') {
  722. scnr.next();
  723. value += `-${getDigits(scnr)}`;
  724. }
  725. else {
  726. value += getDigits(scnr);
  727. }
  728. if (scnr.currentChar() === EOF) {
  729. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  730. }
  731. return value;
  732. }
  733. function isLiteral(ch) {
  734. return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
  735. }
  736. function readLiteral(scnr) {
  737. skipSpaces(scnr);
  738. // eslint-disable-next-line no-useless-escape
  739. eat(scnr, `\'`);
  740. let ch = '';
  741. let literal = '';
  742. while ((ch = takeChar(scnr, isLiteral))) {
  743. if (ch === '\\') {
  744. literal += readEscapeSequence(scnr);
  745. }
  746. else {
  747. literal += ch;
  748. }
  749. }
  750. const current = scnr.currentChar();
  751. if (current === CHAR_LF || current === EOF) {
  752. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  753. // TODO: Is it correct really?
  754. if (current === CHAR_LF) {
  755. scnr.next();
  756. // eslint-disable-next-line no-useless-escape
  757. eat(scnr, `\'`);
  758. }
  759. return literal;
  760. }
  761. // eslint-disable-next-line no-useless-escape
  762. eat(scnr, `\'`);
  763. return literal;
  764. }
  765. function readEscapeSequence(scnr) {
  766. const ch = scnr.currentChar();
  767. switch (ch) {
  768. case '\\':
  769. case `\'`: // eslint-disable-line no-useless-escape
  770. scnr.next();
  771. return `\\${ch}`;
  772. case 'u':
  773. return readUnicodeEscapeSequence(scnr, ch, 4);
  774. case 'U':
  775. return readUnicodeEscapeSequence(scnr, ch, 6);
  776. default:
  777. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  778. return '';
  779. }
  780. }
  781. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  782. eat(scnr, unicode);
  783. let sequence = '';
  784. for (let i = 0; i < digits; i++) {
  785. const ch = takeHexDigit(scnr);
  786. if (!ch) {
  787. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  788. break;
  789. }
  790. sequence += ch;
  791. }
  792. return `\\${unicode}${sequence}`;
  793. }
  794. function isInvalidIdentifier(ch) {
  795. return (ch !== "{" /* TokenChars.BraceLeft */ &&
  796. ch !== "}" /* TokenChars.BraceRight */ &&
  797. ch !== CHAR_SP &&
  798. ch !== CHAR_LF);
  799. }
  800. function readInvalidIdentifier(scnr) {
  801. skipSpaces(scnr);
  802. let ch = '';
  803. let identifiers = '';
  804. while ((ch = takeChar(scnr, isInvalidIdentifier))) {
  805. identifiers += ch;
  806. }
  807. return identifiers;
  808. }
  809. function readLinkedModifier(scnr) {
  810. let ch = '';
  811. let name = '';
  812. while ((ch = takeIdentifierChar(scnr))) {
  813. name += ch;
  814. }
  815. return name;
  816. }
  817. function readLinkedRefer(scnr) {
  818. const fn = (buf) => {
  819. const ch = scnr.currentChar();
  820. if (ch === "{" /* TokenChars.BraceLeft */ ||
  821. ch === "%" /* TokenChars.Modulo */ ||
  822. ch === "@" /* TokenChars.LinkedAlias */ ||
  823. ch === "|" /* TokenChars.Pipe */ ||
  824. ch === "(" /* TokenChars.ParenLeft */ ||
  825. ch === ")" /* TokenChars.ParenRight */ ||
  826. !ch) {
  827. return buf;
  828. }
  829. else if (ch === CHAR_SP) {
  830. return buf;
  831. }
  832. else if (ch === CHAR_LF || ch === DOT) {
  833. buf += ch;
  834. scnr.next();
  835. return fn(buf);
  836. }
  837. else {
  838. buf += ch;
  839. scnr.next();
  840. return fn(buf);
  841. }
  842. };
  843. return fn('');
  844. }
  845. function readPlural(scnr) {
  846. skipSpaces(scnr);
  847. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  848. skipSpaces(scnr);
  849. return plural;
  850. }
  851. // TODO: We need refactoring of token parsing ...
  852. function readTokenInPlaceholder(scnr, context) {
  853. let token = null;
  854. const ch = scnr.currentChar();
  855. switch (ch) {
  856. case "{" /* TokenChars.BraceLeft */:
  857. if (context.braceNest >= 1) {
  858. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  859. }
  860. scnr.next();
  861. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  862. skipSpaces(scnr);
  863. context.braceNest++;
  864. return token;
  865. case "}" /* TokenChars.BraceRight */:
  866. if (context.braceNest > 0 &&
  867. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  868. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  869. }
  870. scnr.next();
  871. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  872. context.braceNest--;
  873. context.braceNest > 0 && skipSpaces(scnr);
  874. if (context.inLinked && context.braceNest === 0) {
  875. context.inLinked = false;
  876. }
  877. return token;
  878. case "@" /* TokenChars.LinkedAlias */:
  879. if (context.braceNest > 0) {
  880. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  881. }
  882. token = readTokenInLinked(scnr, context) || getEndToken(context);
  883. context.braceNest = 0;
  884. return token;
  885. default: {
  886. let validNamedIdentifier = true;
  887. let validListIdentifier = true;
  888. let validLiteral = true;
  889. if (isPluralStart(scnr)) {
  890. if (context.braceNest > 0) {
  891. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  892. }
  893. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  894. // reset
  895. context.braceNest = 0;
  896. context.inLinked = false;
  897. return token;
  898. }
  899. if (context.braceNest > 0 &&
  900. (context.currentType === 5 /* TokenTypes.Named */ ||
  901. context.currentType === 6 /* TokenTypes.List */ ||
  902. context.currentType === 7 /* TokenTypes.Literal */)) {
  903. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  904. context.braceNest = 0;
  905. return readToken(scnr, context);
  906. }
  907. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  908. token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  909. skipSpaces(scnr);
  910. return token;
  911. }
  912. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  913. token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
  914. skipSpaces(scnr);
  915. return token;
  916. }
  917. if ((validLiteral = isLiteralStart(scnr, context))) {
  918. token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
  919. skipSpaces(scnr);
  920. return token;
  921. }
  922. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  923. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  924. token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  925. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  926. skipSpaces(scnr);
  927. return token;
  928. }
  929. break;
  930. }
  931. }
  932. return token;
  933. }
  934. // TODO: We need refactoring of token parsing ...
  935. function readTokenInLinked(scnr, context) {
  936. const { currentType } = context;
  937. let token = null;
  938. const ch = scnr.currentChar();
  939. if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
  940. currentType === 9 /* TokenTypes.LinkedDot */ ||
  941. currentType === 12 /* TokenTypes.LinkedModifier */ ||
  942. currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
  943. (ch === CHAR_LF || ch === CHAR_SP)) {
  944. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  945. }
  946. switch (ch) {
  947. case "@" /* TokenChars.LinkedAlias */:
  948. scnr.next();
  949. token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  950. context.inLinked = true;
  951. return token;
  952. case "." /* TokenChars.LinkedDot */:
  953. skipSpaces(scnr);
  954. scnr.next();
  955. return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  956. case ":" /* TokenChars.LinkedDelimiter */:
  957. skipSpaces(scnr);
  958. scnr.next();
  959. return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  960. default:
  961. if (isPluralStart(scnr)) {
  962. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  963. // reset
  964. context.braceNest = 0;
  965. context.inLinked = false;
  966. return token;
  967. }
  968. if (isLinkedDotStart(scnr, context) ||
  969. isLinkedDelimiterStart(scnr, context)) {
  970. skipSpaces(scnr);
  971. return readTokenInLinked(scnr, context);
  972. }
  973. if (isLinkedModifierStart(scnr, context)) {
  974. skipSpaces(scnr);
  975. return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  976. }
  977. if (isLinkedReferStart(scnr, context)) {
  978. skipSpaces(scnr);
  979. if (ch === "{" /* TokenChars.BraceLeft */) {
  980. // scan the placeholder
  981. return readTokenInPlaceholder(scnr, context) || token;
  982. }
  983. else {
  984. return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  985. }
  986. }
  987. if (currentType === 8 /* TokenTypes.LinkedAlias */) {
  988. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  989. }
  990. context.braceNest = 0;
  991. context.inLinked = false;
  992. return readToken(scnr, context);
  993. }
  994. }
  995. // TODO: We need refactoring of token parsing ...
  996. function readToken(scnr, context) {
  997. let token = { type: 14 /* TokenTypes.EOF */ };
  998. if (context.braceNest > 0) {
  999. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1000. }
  1001. if (context.inLinked) {
  1002. return readTokenInLinked(scnr, context) || getEndToken(context);
  1003. }
  1004. const ch = scnr.currentChar();
  1005. switch (ch) {
  1006. case "{" /* TokenChars.BraceLeft */:
  1007. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1008. case "}" /* TokenChars.BraceRight */:
  1009. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  1010. scnr.next();
  1011. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  1012. case "@" /* TokenChars.LinkedAlias */:
  1013. return readTokenInLinked(scnr, context) || getEndToken(context);
  1014. default: {
  1015. if (isPluralStart(scnr)) {
  1016. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  1017. // reset
  1018. context.braceNest = 0;
  1019. context.inLinked = false;
  1020. return token;
  1021. }
  1022. const { isModulo, hasSpace } = detectModuloStart(scnr);
  1023. if (isModulo) {
  1024. return hasSpace
  1025. ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
  1026. : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
  1027. }
  1028. if (isTextStart(scnr)) {
  1029. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  1030. }
  1031. break;
  1032. }
  1033. }
  1034. return token;
  1035. }
  1036. function nextToken() {
  1037. const { currentType, offset, startLoc, endLoc } = _context;
  1038. _context.lastType = currentType;
  1039. _context.lastOffset = offset;
  1040. _context.lastStartLoc = startLoc;
  1041. _context.lastEndLoc = endLoc;
  1042. _context.offset = currentOffset();
  1043. _context.startLoc = currentPosition();
  1044. if (_scnr.currentChar() === EOF) {
  1045. return getToken(_context, 14 /* TokenTypes.EOF */);
  1046. }
  1047. return readToken(_scnr, _context);
  1048. }
  1049. return {
  1050. nextToken,
  1051. currentOffset,
  1052. currentPosition,
  1053. context
  1054. };
  1055. }
  1056. const ERROR_DOMAIN$2 = 'parser';
  1057. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1058. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1059. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1060. switch (match) {
  1061. case `\\\\`:
  1062. return `\\`;
  1063. // eslint-disable-next-line no-useless-escape
  1064. case `\\\'`:
  1065. // eslint-disable-next-line no-useless-escape
  1066. return `\'`;
  1067. default: {
  1068. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1069. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1070. return String.fromCodePoint(codePoint);
  1071. }
  1072. // invalid ...
  1073. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1074. return '�';
  1075. }
  1076. }
  1077. }
  1078. function createParser(options = {}) {
  1079. const location = options.location !== false;
  1080. const { onError, onWarn } = options;
  1081. function emitError(tokenzer, code, start, offset, ...args) {
  1082. const end = tokenzer.currentPosition();
  1083. end.offset += offset;
  1084. end.column += offset;
  1085. if (onError) {
  1086. const loc = location ? createLocation(start, end) : null;
  1087. const err = createCompileError(code, loc, {
  1088. domain: ERROR_DOMAIN$2,
  1089. args
  1090. });
  1091. onError(err);
  1092. }
  1093. }
  1094. function emitWarn(tokenzer, code, start, offset, ...args) {
  1095. const end = tokenzer.currentPosition();
  1096. end.offset += offset;
  1097. end.column += offset;
  1098. if (onWarn) {
  1099. const loc = location ? createLocation(start, end) : null;
  1100. onWarn(createCompileWarn(code, loc, args));
  1101. }
  1102. }
  1103. function startNode(type, offset, loc) {
  1104. const node = { type };
  1105. if (location) {
  1106. node.start = offset;
  1107. node.end = offset;
  1108. node.loc = { start: loc, end: loc };
  1109. }
  1110. return node;
  1111. }
  1112. function endNode(node, offset, pos, type) {
  1113. if (type) {
  1114. node.type = type;
  1115. }
  1116. if (location) {
  1117. node.end = offset;
  1118. if (node.loc) {
  1119. node.loc.end = pos;
  1120. }
  1121. }
  1122. }
  1123. function parseText(tokenizer, value) {
  1124. const context = tokenizer.context();
  1125. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  1126. node.value = value;
  1127. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1128. return node;
  1129. }
  1130. function parseList(tokenizer, index) {
  1131. const context = tokenizer.context();
  1132. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1133. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  1134. node.index = parseInt(index, 10);
  1135. tokenizer.nextToken(); // skip brach right
  1136. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1137. return node;
  1138. }
  1139. function parseNamed(tokenizer, key, modulo) {
  1140. const context = tokenizer.context();
  1141. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1142. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  1143. node.key = key;
  1144. if (modulo === true) {
  1145. node.modulo = true;
  1146. }
  1147. tokenizer.nextToken(); // skip brach right
  1148. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1149. return node;
  1150. }
  1151. function parseLiteral(tokenizer, value) {
  1152. const context = tokenizer.context();
  1153. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1154. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  1155. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1156. tokenizer.nextToken(); // skip brach right
  1157. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1158. return node;
  1159. }
  1160. function parseLinkedModifier(tokenizer) {
  1161. const token = tokenizer.nextToken();
  1162. const context = tokenizer.context();
  1163. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1164. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  1165. if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
  1166. // empty modifier
  1167. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  1168. node.value = '';
  1169. endNode(node, offset, loc);
  1170. return {
  1171. nextConsumeToken: token,
  1172. node
  1173. };
  1174. }
  1175. // check token
  1176. if (token.value == null) {
  1177. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1178. }
  1179. node.value = token.value || '';
  1180. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1181. return {
  1182. node
  1183. };
  1184. }
  1185. function parseLinkedKey(tokenizer, value) {
  1186. const context = tokenizer.context();
  1187. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  1188. node.value = value;
  1189. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1190. return node;
  1191. }
  1192. function parseLinked(tokenizer) {
  1193. const context = tokenizer.context();
  1194. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  1195. let token = tokenizer.nextToken();
  1196. if (token.type === 9 /* TokenTypes.LinkedDot */) {
  1197. const parsed = parseLinkedModifier(tokenizer);
  1198. linkedNode.modifier = parsed.node;
  1199. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1200. }
  1201. // asset check token
  1202. if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
  1203. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1204. }
  1205. token = tokenizer.nextToken();
  1206. // skip brace left
  1207. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  1208. token = tokenizer.nextToken();
  1209. }
  1210. switch (token.type) {
  1211. case 11 /* TokenTypes.LinkedKey */:
  1212. if (token.value == null) {
  1213. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1214. }
  1215. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1216. break;
  1217. case 5 /* TokenTypes.Named */:
  1218. if (token.value == null) {
  1219. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1220. }
  1221. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1222. break;
  1223. case 6 /* TokenTypes.List */:
  1224. if (token.value == null) {
  1225. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1226. }
  1227. linkedNode.key = parseList(tokenizer, token.value || '');
  1228. break;
  1229. case 7 /* TokenTypes.Literal */:
  1230. if (token.value == null) {
  1231. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1232. }
  1233. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1234. break;
  1235. default: {
  1236. // empty key
  1237. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1238. const nextContext = tokenizer.context();
  1239. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1240. emptyLinkedKeyNode.value = '';
  1241. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1242. linkedNode.key = emptyLinkedKeyNode;
  1243. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1244. return {
  1245. nextConsumeToken: token,
  1246. node: linkedNode
  1247. };
  1248. }
  1249. }
  1250. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1251. return {
  1252. node: linkedNode
  1253. };
  1254. }
  1255. function parseMessage(tokenizer) {
  1256. const context = tokenizer.context();
  1257. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1258. ? tokenizer.currentOffset()
  1259. : context.offset;
  1260. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1261. ? context.endLoc
  1262. : context.startLoc;
  1263. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1264. node.items = [];
  1265. let nextToken = null;
  1266. let modulo = null;
  1267. do {
  1268. const token = nextToken || tokenizer.nextToken();
  1269. nextToken = null;
  1270. switch (token.type) {
  1271. case 0 /* TokenTypes.Text */:
  1272. if (token.value == null) {
  1273. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1274. }
  1275. node.items.push(parseText(tokenizer, token.value || ''));
  1276. break;
  1277. case 6 /* TokenTypes.List */:
  1278. if (token.value == null) {
  1279. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1280. }
  1281. node.items.push(parseList(tokenizer, token.value || ''));
  1282. break;
  1283. case 4 /* TokenTypes.Modulo */:
  1284. modulo = true;
  1285. break;
  1286. case 5 /* TokenTypes.Named */:
  1287. if (token.value == null) {
  1288. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1289. }
  1290. node.items.push(parseNamed(tokenizer, token.value || '', !!modulo));
  1291. if (modulo) {
  1292. emitWarn(tokenizer, CompileWarnCodes.USE_MODULO_SYNTAX, context.lastStartLoc, 0, getTokenCaption(token));
  1293. modulo = null;
  1294. }
  1295. break;
  1296. case 7 /* TokenTypes.Literal */:
  1297. if (token.value == null) {
  1298. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1299. }
  1300. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1301. break;
  1302. case 8 /* TokenTypes.LinkedAlias */: {
  1303. const parsed = parseLinked(tokenizer);
  1304. node.items.push(parsed.node);
  1305. nextToken = parsed.nextConsumeToken || null;
  1306. break;
  1307. }
  1308. }
  1309. } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
  1310. context.currentType !== 1 /* TokenTypes.Pipe */);
  1311. // adjust message node loc
  1312. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1313. ? context.lastOffset
  1314. : tokenizer.currentOffset();
  1315. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1316. ? context.lastEndLoc
  1317. : tokenizer.currentPosition();
  1318. endNode(node, endOffset, endLoc);
  1319. return node;
  1320. }
  1321. function parsePlural(tokenizer, offset, loc, msgNode) {
  1322. const context = tokenizer.context();
  1323. let hasEmptyMessage = msgNode.items.length === 0;
  1324. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1325. node.cases = [];
  1326. node.cases.push(msgNode);
  1327. do {
  1328. const msg = parseMessage(tokenizer);
  1329. if (!hasEmptyMessage) {
  1330. hasEmptyMessage = msg.items.length === 0;
  1331. }
  1332. node.cases.push(msg);
  1333. } while (context.currentType !== 14 /* TokenTypes.EOF */);
  1334. if (hasEmptyMessage) {
  1335. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1336. }
  1337. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1338. return node;
  1339. }
  1340. function parseResource(tokenizer) {
  1341. const context = tokenizer.context();
  1342. const { offset, startLoc } = context;
  1343. const msgNode = parseMessage(tokenizer);
  1344. if (context.currentType === 14 /* TokenTypes.EOF */) {
  1345. return msgNode;
  1346. }
  1347. else {
  1348. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1349. }
  1350. }
  1351. function parse(source) {
  1352. const tokenizer = createTokenizer(source, assign({}, options));
  1353. const context = tokenizer.context();
  1354. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1355. if (location && node.loc) {
  1356. node.loc.source = source;
  1357. }
  1358. node.body = parseResource(tokenizer);
  1359. if (options.onCacheKey) {
  1360. node.cacheKey = options.onCacheKey(source);
  1361. }
  1362. // assert whether achieved to EOF
  1363. if (context.currentType !== 14 /* TokenTypes.EOF */) {
  1364. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1365. }
  1366. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1367. return node;
  1368. }
  1369. return { parse };
  1370. }
  1371. function getTokenCaption(token) {
  1372. if (token.type === 14 /* TokenTypes.EOF */) {
  1373. return 'EOF';
  1374. }
  1375. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1376. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1377. }
  1378. function createTransformer(ast, options = {} // eslint-disable-line
  1379. ) {
  1380. const _context = {
  1381. ast,
  1382. helpers: new Set()
  1383. };
  1384. const context = () => _context;
  1385. const helper = (name) => {
  1386. _context.helpers.add(name);
  1387. return name;
  1388. };
  1389. return { context, helper };
  1390. }
  1391. function traverseNodes(nodes, transformer) {
  1392. for (let i = 0; i < nodes.length; i++) {
  1393. traverseNode(nodes[i], transformer);
  1394. }
  1395. }
  1396. function traverseNode(node, transformer) {
  1397. // TODO: if we need pre-hook of transform, should be implemented to here
  1398. switch (node.type) {
  1399. case 1 /* NodeTypes.Plural */:
  1400. traverseNodes(node.cases, transformer);
  1401. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1402. break;
  1403. case 2 /* NodeTypes.Message */:
  1404. traverseNodes(node.items, transformer);
  1405. break;
  1406. case 6 /* NodeTypes.Linked */: {
  1407. const linked = node;
  1408. traverseNode(linked.key, transformer);
  1409. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1410. transformer.helper("type" /* HelperNameMap.TYPE */);
  1411. break;
  1412. }
  1413. case 5 /* NodeTypes.List */:
  1414. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1415. transformer.helper("list" /* HelperNameMap.LIST */);
  1416. break;
  1417. case 4 /* NodeTypes.Named */:
  1418. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1419. transformer.helper("named" /* HelperNameMap.NAMED */);
  1420. break;
  1421. }
  1422. // TODO: if we need post-hook of transform, should be implemented to here
  1423. }
  1424. // transform AST
  1425. function transform(ast, options = {} // eslint-disable-line
  1426. ) {
  1427. const transformer = createTransformer(ast);
  1428. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1429. // traverse
  1430. ast.body && traverseNode(ast.body, transformer);
  1431. // set meta information
  1432. const context = transformer.context();
  1433. ast.helpers = Array.from(context.helpers);
  1434. }
  1435. function optimize(ast) {
  1436. const body = ast.body;
  1437. if (body.type === 2 /* NodeTypes.Message */) {
  1438. optimizeMessageNode(body);
  1439. }
  1440. else {
  1441. body.cases.forEach(c => optimizeMessageNode(c));
  1442. }
  1443. return ast;
  1444. }
  1445. function optimizeMessageNode(message) {
  1446. if (message.items.length === 1) {
  1447. const item = message.items[0];
  1448. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1449. message.static = item.value;
  1450. delete item.value; // optimization for size
  1451. }
  1452. }
  1453. else {
  1454. const values = [];
  1455. for (let i = 0; i < message.items.length; i++) {
  1456. const item = message.items[i];
  1457. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1458. break;
  1459. }
  1460. if (item.value == null) {
  1461. break;
  1462. }
  1463. values.push(item.value);
  1464. }
  1465. if (values.length === message.items.length) {
  1466. message.static = join(values);
  1467. for (let i = 0; i < message.items.length; i++) {
  1468. const item = message.items[i];
  1469. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1470. delete item.value; // optimization for size
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. const ERROR_DOMAIN$1 = 'minifier';
  1477. /* eslint-disable @typescript-eslint/no-explicit-any */
  1478. function minify(node) {
  1479. node.t = node.type;
  1480. switch (node.type) {
  1481. case 0 /* NodeTypes.Resource */: {
  1482. const resource = node;
  1483. minify(resource.body);
  1484. resource.b = resource.body;
  1485. delete resource.body;
  1486. break;
  1487. }
  1488. case 1 /* NodeTypes.Plural */: {
  1489. const plural = node;
  1490. const cases = plural.cases;
  1491. for (let i = 0; i < cases.length; i++) {
  1492. minify(cases[i]);
  1493. }
  1494. plural.c = cases;
  1495. delete plural.cases;
  1496. break;
  1497. }
  1498. case 2 /* NodeTypes.Message */: {
  1499. const message = node;
  1500. const items = message.items;
  1501. for (let i = 0; i < items.length; i++) {
  1502. minify(items[i]);
  1503. }
  1504. message.i = items;
  1505. delete message.items;
  1506. if (message.static) {
  1507. message.s = message.static;
  1508. delete message.static;
  1509. }
  1510. break;
  1511. }
  1512. case 3 /* NodeTypes.Text */:
  1513. case 9 /* NodeTypes.Literal */:
  1514. case 8 /* NodeTypes.LinkedModifier */:
  1515. case 7 /* NodeTypes.LinkedKey */: {
  1516. const valueNode = node;
  1517. if (valueNode.value) {
  1518. valueNode.v = valueNode.value;
  1519. delete valueNode.value;
  1520. }
  1521. break;
  1522. }
  1523. case 6 /* NodeTypes.Linked */: {
  1524. const linked = node;
  1525. minify(linked.key);
  1526. linked.k = linked.key;
  1527. delete linked.key;
  1528. if (linked.modifier) {
  1529. minify(linked.modifier);
  1530. linked.m = linked.modifier;
  1531. delete linked.modifier;
  1532. }
  1533. break;
  1534. }
  1535. case 5 /* NodeTypes.List */: {
  1536. const list = node;
  1537. list.i = list.index;
  1538. delete list.index;
  1539. break;
  1540. }
  1541. case 4 /* NodeTypes.Named */: {
  1542. const named = node;
  1543. named.k = named.key;
  1544. delete named.key;
  1545. break;
  1546. }
  1547. default:
  1548. {
  1549. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1550. domain: ERROR_DOMAIN$1,
  1551. args: [node.type]
  1552. });
  1553. }
  1554. }
  1555. delete node.type;
  1556. }
  1557. /* eslint-enable @typescript-eslint/no-explicit-any */
  1558. // eslint-disable-next-line @typescript-eslint/triple-slash-reference
  1559. /// <reference types="source-map-js" />
  1560. const ERROR_DOMAIN = 'parser';
  1561. function createCodeGenerator(ast, options) {
  1562. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1563. const location = options.location !== false;
  1564. const _context = {
  1565. filename,
  1566. code: '',
  1567. column: 1,
  1568. line: 1,
  1569. offset: 0,
  1570. map: undefined,
  1571. breakLineCode,
  1572. needIndent: _needIndent,
  1573. indentLevel: 0
  1574. };
  1575. if (location && ast.loc) {
  1576. _context.source = ast.loc.source;
  1577. }
  1578. const context = () => _context;
  1579. function push(code, node) {
  1580. _context.code += code;
  1581. }
  1582. function _newline(n, withBreakLine = true) {
  1583. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1584. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1585. }
  1586. function indent(withNewLine = true) {
  1587. const level = ++_context.indentLevel;
  1588. withNewLine && _newline(level);
  1589. }
  1590. function deindent(withNewLine = true) {
  1591. const level = --_context.indentLevel;
  1592. withNewLine && _newline(level);
  1593. }
  1594. function newline() {
  1595. _newline(_context.indentLevel);
  1596. }
  1597. const helper = (key) => `_${key}`;
  1598. const needIndent = () => _context.needIndent;
  1599. return {
  1600. context,
  1601. push,
  1602. indent,
  1603. deindent,
  1604. newline,
  1605. helper,
  1606. needIndent
  1607. };
  1608. }
  1609. function generateLinkedNode(generator, node) {
  1610. const { helper } = generator;
  1611. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1612. generateNode(generator, node.key);
  1613. if (node.modifier) {
  1614. generator.push(`, `);
  1615. generateNode(generator, node.modifier);
  1616. generator.push(`, _type`);
  1617. }
  1618. else {
  1619. generator.push(`, undefined, _type`);
  1620. }
  1621. generator.push(`)`);
  1622. }
  1623. function generateMessageNode(generator, node) {
  1624. const { helper, needIndent } = generator;
  1625. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1626. generator.indent(needIndent());
  1627. const length = node.items.length;
  1628. for (let i = 0; i < length; i++) {
  1629. generateNode(generator, node.items[i]);
  1630. if (i === length - 1) {
  1631. break;
  1632. }
  1633. generator.push(', ');
  1634. }
  1635. generator.deindent(needIndent());
  1636. generator.push('])');
  1637. }
  1638. function generatePluralNode(generator, node) {
  1639. const { helper, needIndent } = generator;
  1640. if (node.cases.length > 1) {
  1641. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1642. generator.indent(needIndent());
  1643. const length = node.cases.length;
  1644. for (let i = 0; i < length; i++) {
  1645. generateNode(generator, node.cases[i]);
  1646. if (i === length - 1) {
  1647. break;
  1648. }
  1649. generator.push(', ');
  1650. }
  1651. generator.deindent(needIndent());
  1652. generator.push(`])`);
  1653. }
  1654. }
  1655. function generateResource(generator, node) {
  1656. if (node.body) {
  1657. generateNode(generator, node.body);
  1658. }
  1659. else {
  1660. generator.push('null');
  1661. }
  1662. }
  1663. function generateNode(generator, node) {
  1664. const { helper } = generator;
  1665. switch (node.type) {
  1666. case 0 /* NodeTypes.Resource */:
  1667. generateResource(generator, node);
  1668. break;
  1669. case 1 /* NodeTypes.Plural */:
  1670. generatePluralNode(generator, node);
  1671. break;
  1672. case 2 /* NodeTypes.Message */:
  1673. generateMessageNode(generator, node);
  1674. break;
  1675. case 6 /* NodeTypes.Linked */:
  1676. generateLinkedNode(generator, node);
  1677. break;
  1678. case 8 /* NodeTypes.LinkedModifier */:
  1679. generator.push(JSON.stringify(node.value), node);
  1680. break;
  1681. case 7 /* NodeTypes.LinkedKey */:
  1682. generator.push(JSON.stringify(node.value), node);
  1683. break;
  1684. case 5 /* NodeTypes.List */:
  1685. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1686. break;
  1687. case 4 /* NodeTypes.Named */:
  1688. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1689. break;
  1690. case 9 /* NodeTypes.Literal */:
  1691. generator.push(JSON.stringify(node.value), node);
  1692. break;
  1693. case 3 /* NodeTypes.Text */:
  1694. generator.push(JSON.stringify(node.value), node);
  1695. break;
  1696. default:
  1697. {
  1698. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1699. domain: ERROR_DOMAIN,
  1700. args: [node.type]
  1701. });
  1702. }
  1703. }
  1704. }
  1705. // generate code from AST
  1706. const generate = (ast, options = {} // eslint-disable-line
  1707. ) => {
  1708. const mode = isString(options.mode) ? options.mode : 'normal';
  1709. const filename = isString(options.filename)
  1710. ? options.filename
  1711. : 'message.intl';
  1712. const sourceMap = !!options.sourceMap;
  1713. // prettier-ignore
  1714. const breakLineCode = options.breakLineCode != null
  1715. ? options.breakLineCode
  1716. : mode === 'arrow'
  1717. ? ';'
  1718. : '\n';
  1719. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1720. const helpers = ast.helpers || [];
  1721. const generator = createCodeGenerator(ast, {
  1722. mode,
  1723. filename,
  1724. sourceMap,
  1725. breakLineCode,
  1726. needIndent
  1727. });
  1728. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1729. generator.indent(needIndent);
  1730. if (helpers.length > 0) {
  1731. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1732. generator.newline();
  1733. }
  1734. generator.push(`return `);
  1735. generateNode(generator, ast);
  1736. generator.deindent(needIndent);
  1737. generator.push(`}`);
  1738. delete ast.helpers;
  1739. const { code, map } = generator.context();
  1740. return {
  1741. ast,
  1742. code,
  1743. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1744. };
  1745. };
  1746. function baseCompile$1(source, options = {}) {
  1747. const assignedOptions = assign({}, options);
  1748. const jit = !!assignedOptions.jit;
  1749. const enalbeMinify = !!assignedOptions.minify;
  1750. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1751. // parse source codes
  1752. const parser = createParser(assignedOptions);
  1753. const ast = parser.parse(source);
  1754. if (!jit) {
  1755. // transform ASTs
  1756. transform(ast, assignedOptions);
  1757. // generate javascript codes
  1758. return generate(ast, assignedOptions);
  1759. }
  1760. else {
  1761. // optimize ASTs
  1762. enambeOptimize && optimize(ast);
  1763. // minimize ASTs
  1764. enalbeMinify && minify(ast);
  1765. // In JIT mode, no ast transform, no code generation.
  1766. return { ast, code: '' };
  1767. }
  1768. }
  1769. function isMessageAST(val) {
  1770. return (isObject(val) &&
  1771. resolveType(val) === 0 &&
  1772. (hasOwn(val, 'b') || hasOwn(val, 'body')));
  1773. }
  1774. const PROPS_BODY = ['b', 'body'];
  1775. function resolveBody(node) {
  1776. return resolveProps(node, PROPS_BODY);
  1777. }
  1778. const PROPS_CASES = ['c', 'cases'];
  1779. function resolveCases(node) {
  1780. return resolveProps(node, PROPS_CASES, []);
  1781. }
  1782. const PROPS_STATIC = ['s', 'static'];
  1783. function resolveStatic(node) {
  1784. return resolveProps(node, PROPS_STATIC);
  1785. }
  1786. const PROPS_ITEMS = ['i', 'items'];
  1787. function resolveItems(node) {
  1788. return resolveProps(node, PROPS_ITEMS, []);
  1789. }
  1790. const PROPS_TYPE = ['t', 'type'];
  1791. function resolveType(node) {
  1792. return resolveProps(node, PROPS_TYPE);
  1793. }
  1794. const PROPS_VALUE = ['v', 'value'];
  1795. function resolveValue$1(node, type) {
  1796. const resolved = resolveProps(node, PROPS_VALUE);
  1797. if (resolved != null) {
  1798. return resolved;
  1799. }
  1800. else {
  1801. throw createUnhandleNodeError(type);
  1802. }
  1803. }
  1804. const PROPS_MODIFIER = ['m', 'modifier'];
  1805. function resolveLinkedModifier(node) {
  1806. return resolveProps(node, PROPS_MODIFIER);
  1807. }
  1808. const PROPS_KEY = ['k', 'key'];
  1809. function resolveLinkedKey(node) {
  1810. const resolved = resolveProps(node, PROPS_KEY);
  1811. if (resolved) {
  1812. return resolved;
  1813. }
  1814. else {
  1815. throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
  1816. }
  1817. }
  1818. function resolveProps(node, props, defaultValue) {
  1819. for (let i = 0; i < props.length; i++) {
  1820. const prop = props[i];
  1821. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1822. if (hasOwn(node, prop) && node[prop] != null) {
  1823. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1824. return node[prop];
  1825. }
  1826. }
  1827. return defaultValue;
  1828. }
  1829. const AST_NODE_PROPS_KEYS = [
  1830. ...PROPS_BODY,
  1831. ...PROPS_CASES,
  1832. ...PROPS_STATIC,
  1833. ...PROPS_ITEMS,
  1834. ...PROPS_KEY,
  1835. ...PROPS_MODIFIER,
  1836. ...PROPS_VALUE,
  1837. ...PROPS_TYPE
  1838. ];
  1839. function createUnhandleNodeError(type) {
  1840. return new Error(`unhandled node type: ${type}`);
  1841. }
  1842. const pathStateMachine = [];
  1843. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  1844. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  1845. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1846. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1847. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1848. };
  1849. pathStateMachine[1 /* States.IN_PATH */] = {
  1850. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  1851. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  1852. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1853. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1854. };
  1855. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  1856. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  1857. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1858. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  1859. };
  1860. pathStateMachine[3 /* States.IN_IDENT */] = {
  1861. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1862. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1863. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  1864. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  1865. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  1866. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  1867. };
  1868. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  1869. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  1870. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  1871. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  1872. 4 /* States.IN_SUB_PATH */,
  1873. 2 /* Actions.INC_SUB_PATH_DEPTH */
  1874. ],
  1875. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  1876. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1877. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  1878. };
  1879. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  1880. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1881. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1882. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  1883. };
  1884. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  1885. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1886. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1887. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  1888. };
  1889. /**
  1890. * Check if an expression is a literal value.
  1891. */
  1892. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  1893. function isLiteral(exp) {
  1894. return literalValueRE.test(exp);
  1895. }
  1896. /**
  1897. * Strip quotes from a string
  1898. */
  1899. function stripQuotes(str) {
  1900. const a = str.charCodeAt(0);
  1901. const b = str.charCodeAt(str.length - 1);
  1902. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  1903. }
  1904. /**
  1905. * Determine the type of a character in a keypath.
  1906. */
  1907. function getPathCharType(ch) {
  1908. if (ch === undefined || ch === null) {
  1909. return "o" /* PathCharTypes.END_OF_FAIL */;
  1910. }
  1911. const code = ch.charCodeAt(0);
  1912. switch (code) {
  1913. case 0x5b: // [
  1914. case 0x5d: // ]
  1915. case 0x2e: // .
  1916. case 0x22: // "
  1917. case 0x27: // '
  1918. return ch;
  1919. case 0x5f: // _
  1920. case 0x24: // $
  1921. case 0x2d: // -
  1922. return "i" /* PathCharTypes.IDENT */;
  1923. case 0x09: // Tab (HT)
  1924. case 0x0a: // Newline (LF)
  1925. case 0x0d: // Return (CR)
  1926. case 0xa0: // No-break space (NBSP)
  1927. case 0xfeff: // Byte Order Mark (BOM)
  1928. case 0x2028: // Line Separator (LS)
  1929. case 0x2029: // Paragraph Separator (PS)
  1930. return "w" /* PathCharTypes.WORKSPACE */;
  1931. }
  1932. return "i" /* PathCharTypes.IDENT */;
  1933. }
  1934. /**
  1935. * Format a subPath, return its plain form if it is
  1936. * a literal string or number. Otherwise prepend the
  1937. * dynamic indicator (*).
  1938. */
  1939. function formatSubPath(path) {
  1940. const trimmed = path.trim();
  1941. // invalid leading 0
  1942. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  1943. return false;
  1944. }
  1945. return isLiteral(trimmed)
  1946. ? stripQuotes(trimmed)
  1947. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  1948. }
  1949. /**
  1950. * Parse a string path into an array of segments
  1951. */
  1952. function parse(path) {
  1953. const keys = [];
  1954. let index = -1;
  1955. let mode = 0 /* States.BEFORE_PATH */;
  1956. let subPathDepth = 0;
  1957. let c;
  1958. let key; // eslint-disable-line
  1959. let newChar;
  1960. let type;
  1961. let transition;
  1962. let action;
  1963. let typeMap;
  1964. const actions = [];
  1965. actions[0 /* Actions.APPEND */] = () => {
  1966. if (key === undefined) {
  1967. key = newChar;
  1968. }
  1969. else {
  1970. key += newChar;
  1971. }
  1972. };
  1973. actions[1 /* Actions.PUSH */] = () => {
  1974. if (key !== undefined) {
  1975. keys.push(key);
  1976. key = undefined;
  1977. }
  1978. };
  1979. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  1980. actions[0 /* Actions.APPEND */]();
  1981. subPathDepth++;
  1982. };
  1983. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  1984. if (subPathDepth > 0) {
  1985. subPathDepth--;
  1986. mode = 4 /* States.IN_SUB_PATH */;
  1987. actions[0 /* Actions.APPEND */]();
  1988. }
  1989. else {
  1990. subPathDepth = 0;
  1991. if (key === undefined) {
  1992. return false;
  1993. }
  1994. key = formatSubPath(key);
  1995. if (key === false) {
  1996. return false;
  1997. }
  1998. else {
  1999. actions[1 /* Actions.PUSH */]();
  2000. }
  2001. }
  2002. };
  2003. function maybeUnescapeQuote() {
  2004. const nextChar = path[index + 1];
  2005. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  2006. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  2007. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  2008. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  2009. index++;
  2010. newChar = '\\' + nextChar;
  2011. actions[0 /* Actions.APPEND */]();
  2012. return true;
  2013. }
  2014. }
  2015. while (mode !== null) {
  2016. index++;
  2017. c = path[index];
  2018. if (c === '\\' && maybeUnescapeQuote()) {
  2019. continue;
  2020. }
  2021. type = getPathCharType(c);
  2022. typeMap = pathStateMachine[mode];
  2023. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  2024. // check parse error
  2025. if (transition === 8 /* States.ERROR */) {
  2026. return;
  2027. }
  2028. mode = transition[0];
  2029. if (transition[1] !== undefined) {
  2030. action = actions[transition[1]];
  2031. if (action) {
  2032. newChar = c;
  2033. if (action() === false) {
  2034. return;
  2035. }
  2036. }
  2037. }
  2038. // check parse finish
  2039. if (mode === 7 /* States.AFTER_PATH */) {
  2040. return keys;
  2041. }
  2042. }
  2043. }
  2044. // path token cache
  2045. const cache = new Map();
  2046. /**
  2047. * key-value message resolver
  2048. *
  2049. * @remarks
  2050. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  2051. *
  2052. * @param obj - A target object to be resolved with path
  2053. * @param path - A {@link Path | path} to resolve the value of message
  2054. *
  2055. * @returns A resolved {@link PathValue | path value}
  2056. *
  2057. * @VueI18nGeneral
  2058. */
  2059. function resolveWithKeyValue(obj, path) {
  2060. return isObject(obj) ? obj[path] : null;
  2061. }
  2062. /**
  2063. * message resolver
  2064. *
  2065. * @remarks
  2066. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  2067. *
  2068. * @param obj - A target object to be resolved with path
  2069. * @param path - A {@link Path | path} to resolve the value of message
  2070. *
  2071. * @returns A resolved {@link PathValue | path value}
  2072. *
  2073. * @VueI18nGeneral
  2074. */
  2075. function resolveValue(obj, path) {
  2076. // check object
  2077. if (!isObject(obj)) {
  2078. return null;
  2079. }
  2080. // parse path
  2081. let hit = cache.get(path);
  2082. if (!hit) {
  2083. hit = parse(path);
  2084. if (hit) {
  2085. cache.set(path, hit);
  2086. }
  2087. }
  2088. // check hit
  2089. if (!hit) {
  2090. return null;
  2091. }
  2092. // resolve path value
  2093. const len = hit.length;
  2094. let last = obj;
  2095. let i = 0;
  2096. while (i < len) {
  2097. const key = hit[i];
  2098. /**
  2099. * NOTE:
  2100. * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
  2101. * because the AST node is not a key-value structure.
  2102. */
  2103. if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
  2104. return null;
  2105. }
  2106. const val = last[key];
  2107. if (val === undefined) {
  2108. return null;
  2109. }
  2110. if (isFunction(last)) {
  2111. return null;
  2112. }
  2113. last = val;
  2114. i++;
  2115. }
  2116. return last;
  2117. }
  2118. const DEFAULT_MODIFIER = (str) => str;
  2119. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  2120. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  2121. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  2122. const DEFAULT_INTERPOLATE = toDisplayString;
  2123. function pluralDefault(choice, choicesLength) {
  2124. choice = Math.abs(choice);
  2125. if (choicesLength === 2) {
  2126. // prettier-ignore
  2127. return choice
  2128. ? choice > 1
  2129. ? 1
  2130. : 0
  2131. : 1;
  2132. }
  2133. return choice ? Math.min(choice, 2) : 0;
  2134. }
  2135. function getPluralIndex(options) {
  2136. // prettier-ignore
  2137. const index = isNumber(options.pluralIndex)
  2138. ? options.pluralIndex
  2139. : -1;
  2140. // prettier-ignore
  2141. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  2142. ? isNumber(options.named.count)
  2143. ? options.named.count
  2144. : isNumber(options.named.n)
  2145. ? options.named.n
  2146. : index
  2147. : index;
  2148. }
  2149. function normalizeNamed(pluralIndex, props) {
  2150. if (!props.count) {
  2151. props.count = pluralIndex;
  2152. }
  2153. if (!props.n) {
  2154. props.n = pluralIndex;
  2155. }
  2156. }
  2157. function createMessageContext(options = {}) {
  2158. const locale = options.locale;
  2159. const pluralIndex = getPluralIndex(options);
  2160. const pluralRule = isObject(options.pluralRules) &&
  2161. isString(locale) &&
  2162. isFunction(options.pluralRules[locale])
  2163. ? options.pluralRules[locale]
  2164. : pluralDefault;
  2165. const orgPluralRule = isObject(options.pluralRules) &&
  2166. isString(locale) &&
  2167. isFunction(options.pluralRules[locale])
  2168. ? pluralDefault
  2169. : undefined;
  2170. const plural = (messages) => {
  2171. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  2172. };
  2173. const _list = options.list || [];
  2174. const list = (index) => _list[index];
  2175. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2176. const _named = options.named || create();
  2177. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  2178. const named = (key) => _named[key];
  2179. function message(key) {
  2180. // prettier-ignore
  2181. const msg = isFunction(options.messages)
  2182. ? options.messages(key)
  2183. : isObject(options.messages)
  2184. ? options.messages[key]
  2185. : false;
  2186. return !msg
  2187. ? options.parent
  2188. ? options.parent.message(key) // resolve from parent messages
  2189. : DEFAULT_MESSAGE
  2190. : msg;
  2191. }
  2192. const _modifier = (name) => options.modifiers
  2193. ? options.modifiers[name]
  2194. : DEFAULT_MODIFIER;
  2195. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  2196. ? options.processor.normalize
  2197. : DEFAULT_NORMALIZE;
  2198. const interpolate = isPlainObject(options.processor) &&
  2199. isFunction(options.processor.interpolate)
  2200. ? options.processor.interpolate
  2201. : DEFAULT_INTERPOLATE;
  2202. const type = isPlainObject(options.processor) && isString(options.processor.type)
  2203. ? options.processor.type
  2204. : DEFAULT_MESSAGE_DATA_TYPE;
  2205. const linked = (key, ...args) => {
  2206. const [arg1, arg2] = args;
  2207. let type = 'text';
  2208. let modifier = '';
  2209. if (args.length === 1) {
  2210. if (isObject(arg1)) {
  2211. modifier = arg1.modifier || modifier;
  2212. type = arg1.type || type;
  2213. }
  2214. else if (isString(arg1)) {
  2215. modifier = arg1 || modifier;
  2216. }
  2217. }
  2218. else if (args.length === 2) {
  2219. if (isString(arg1)) {
  2220. modifier = arg1 || modifier;
  2221. }
  2222. if (isString(arg2)) {
  2223. type = arg2 || type;
  2224. }
  2225. }
  2226. const ret = message(key)(ctx);
  2227. const msg =
  2228. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  2229. type === 'vnode' && isArray(ret) && modifier
  2230. ? ret[0]
  2231. : ret;
  2232. return modifier ? _modifier(modifier)(msg, type) : msg;
  2233. };
  2234. const ctx = {
  2235. ["list" /* HelperNameMap.LIST */]: list,
  2236. ["named" /* HelperNameMap.NAMED */]: named,
  2237. ["plural" /* HelperNameMap.PLURAL */]: plural,
  2238. ["linked" /* HelperNameMap.LINKED */]: linked,
  2239. ["message" /* HelperNameMap.MESSAGE */]: message,
  2240. ["type" /* HelperNameMap.TYPE */]: type,
  2241. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  2242. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  2243. ["values" /* HelperNameMap.VALUES */]: assign(create(), _list, _named)
  2244. };
  2245. return ctx;
  2246. }
  2247. let devtools = null;
  2248. function setDevToolsHook(hook) {
  2249. devtools = hook;
  2250. }
  2251. function getDevToolsHook() {
  2252. return devtools;
  2253. }
  2254. function initI18nDevTools(i18n, version, meta) {
  2255. // TODO: queue if devtools is undefined
  2256. devtools &&
  2257. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  2258. timestamp: Date.now(),
  2259. i18n,
  2260. version,
  2261. meta
  2262. });
  2263. }
  2264. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  2265. function createDevToolsHook(hook) {
  2266. return (payloads) => devtools && devtools.emit(hook, payloads);
  2267. }
  2268. const code$1 = CompileWarnCodes.__EXTEND_POINT__;
  2269. const inc$1 = incrementer(code$1);
  2270. const CoreWarnCodes = {
  2271. NOT_FOUND_KEY: code$1, // 2
  2272. FALLBACK_TO_TRANSLATE: inc$1(), // 3
  2273. CANNOT_FORMAT_NUMBER: inc$1(), // 4
  2274. FALLBACK_TO_NUMBER_FORMAT: inc$1(), // 5
  2275. CANNOT_FORMAT_DATE: inc$1(), // 6
  2276. FALLBACK_TO_DATE_FORMAT: inc$1(), // 7
  2277. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(), // 8
  2278. __EXTEND_POINT__: inc$1() // 9
  2279. };
  2280. /** @internal */
  2281. const warnMessages = {
  2282. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  2283. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  2284. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  2285. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  2286. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  2287. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  2288. [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.`
  2289. };
  2290. function getWarnMessage(code, ...args) {
  2291. return format$1(warnMessages[code], ...args);
  2292. }
  2293. const code = CompileErrorCodes.__EXTEND_POINT__;
  2294. const inc = incrementer(code);
  2295. const CoreErrorCodes = {
  2296. INVALID_ARGUMENT: code, // 17
  2297. INVALID_DATE_ARGUMENT: inc(), // 18
  2298. INVALID_ISO_DATE_ARGUMENT: inc(), // 19
  2299. NOT_SUPPORT_NON_STRING_MESSAGE: inc(), // 20
  2300. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(), // 21
  2301. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(), // 22
  2302. NOT_SUPPORT_LOCALE_TYPE: inc(), // 23
  2303. __EXTEND_POINT__: inc() // 24
  2304. };
  2305. function createCoreError(code) {
  2306. return createCompileError(code, null, { messages: errorMessages } );
  2307. }
  2308. /** @internal */
  2309. const errorMessages = {
  2310. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  2311. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  2312. 'Make sure your Date represents a valid date.',
  2313. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  2314. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  2315. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  2316. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  2317. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  2318. };
  2319. /** @internal */
  2320. function getLocale(context, options) {
  2321. return options.locale != null
  2322. ? resolveLocale(options.locale)
  2323. : resolveLocale(context.locale);
  2324. }
  2325. let _resolveLocale;
  2326. /** @internal */
  2327. function resolveLocale(locale) {
  2328. if (isString(locale)) {
  2329. return locale;
  2330. }
  2331. else {
  2332. if (isFunction(locale)) {
  2333. if (locale.resolvedOnce && _resolveLocale != null) {
  2334. return _resolveLocale;
  2335. }
  2336. else if (locale.constructor.name === 'Function') {
  2337. const resolve = locale();
  2338. if (isPromise(resolve)) {
  2339. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  2340. }
  2341. return (_resolveLocale = resolve);
  2342. }
  2343. else {
  2344. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  2345. }
  2346. }
  2347. else {
  2348. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  2349. }
  2350. }
  2351. }
  2352. /**
  2353. * Fallback with simple implemenation
  2354. *
  2355. * @remarks
  2356. * A fallback locale function implemented with a simple fallback algorithm.
  2357. *
  2358. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  2359. *
  2360. * @param ctx - A {@link CoreContext | context}
  2361. * @param fallback - A {@link FallbackLocale | fallback locale}
  2362. * @param start - A starting {@link Locale | locale}
  2363. *
  2364. * @returns Fallback locales
  2365. *
  2366. * @VueI18nGeneral
  2367. */
  2368. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  2369. ) {
  2370. // prettier-ignore
  2371. return [...new Set([
  2372. start,
  2373. ...(isArray(fallback)
  2374. ? fallback
  2375. : isObject(fallback)
  2376. ? Object.keys(fallback)
  2377. : isString(fallback)
  2378. ? [fallback]
  2379. : [start])
  2380. ])];
  2381. }
  2382. /**
  2383. * Fallback with locale chain
  2384. *
  2385. * @remarks
  2386. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  2387. *
  2388. * @param ctx - A {@link CoreContext | context}
  2389. * @param fallback - A {@link FallbackLocale | fallback locale}
  2390. * @param start - A starting {@link Locale | locale}
  2391. *
  2392. * @returns Fallback locales
  2393. *
  2394. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  2395. *
  2396. * @VueI18nGeneral
  2397. */
  2398. function fallbackWithLocaleChain(ctx, fallback, start) {
  2399. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  2400. const context = ctx;
  2401. if (!context.__localeChainCache) {
  2402. context.__localeChainCache = new Map();
  2403. }
  2404. let chain = context.__localeChainCache.get(startLocale);
  2405. if (!chain) {
  2406. chain = [];
  2407. // first block defined by start
  2408. let block = [start];
  2409. // while any intervening block found
  2410. while (isArray(block)) {
  2411. block = appendBlockToChain(chain, block, fallback);
  2412. }
  2413. // prettier-ignore
  2414. // last block defined by default
  2415. const defaults = isArray(fallback) || !isPlainObject(fallback)
  2416. ? fallback
  2417. : fallback['default']
  2418. ? fallback['default']
  2419. : null;
  2420. // convert defaults to array
  2421. block = isString(defaults) ? [defaults] : defaults;
  2422. if (isArray(block)) {
  2423. appendBlockToChain(chain, block, false);
  2424. }
  2425. context.__localeChainCache.set(startLocale, chain);
  2426. }
  2427. return chain;
  2428. }
  2429. function appendBlockToChain(chain, block, blocks) {
  2430. let follow = true;
  2431. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2432. const locale = block[i];
  2433. if (isString(locale)) {
  2434. follow = appendLocaleToChain(chain, block[i], blocks);
  2435. }
  2436. }
  2437. return follow;
  2438. }
  2439. function appendLocaleToChain(chain, locale, blocks) {
  2440. let follow;
  2441. const tokens = locale.split('-');
  2442. do {
  2443. const target = tokens.join('-');
  2444. follow = appendItemToChain(chain, target, blocks);
  2445. tokens.splice(-1, 1);
  2446. } while (tokens.length && follow === true);
  2447. return follow;
  2448. }
  2449. function appendItemToChain(chain, target, blocks) {
  2450. let follow = false;
  2451. if (!chain.includes(target)) {
  2452. follow = true;
  2453. if (target) {
  2454. follow = target[target.length - 1] !== '!';
  2455. const locale = target.replace(/!/g, '');
  2456. chain.push(locale);
  2457. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2458. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2459. ) {
  2460. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2461. follow = blocks[locale];
  2462. }
  2463. }
  2464. }
  2465. return follow;
  2466. }
  2467. /* eslint-disable @typescript-eslint/no-explicit-any */
  2468. /**
  2469. * Intlify core-base version
  2470. * @internal
  2471. */
  2472. const VERSION = '9.14.5';
  2473. const NOT_REOSLVED = -1;
  2474. const DEFAULT_LOCALE = 'en-US';
  2475. const MISSING_RESOLVE_VALUE = '';
  2476. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  2477. function getDefaultLinkedModifiers() {
  2478. return {
  2479. upper: (val, type) => {
  2480. // prettier-ignore
  2481. return type === 'text' && isString(val)
  2482. ? val.toUpperCase()
  2483. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2484. ? val.children.toUpperCase()
  2485. : val;
  2486. },
  2487. lower: (val, type) => {
  2488. // prettier-ignore
  2489. return type === 'text' && isString(val)
  2490. ? val.toLowerCase()
  2491. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2492. ? val.children.toLowerCase()
  2493. : val;
  2494. },
  2495. capitalize: (val, type) => {
  2496. // prettier-ignore
  2497. return (type === 'text' && isString(val)
  2498. ? capitalize(val)
  2499. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2500. ? capitalize(val.children)
  2501. : val);
  2502. }
  2503. };
  2504. }
  2505. let _compiler;
  2506. function registerMessageCompiler(compiler) {
  2507. _compiler = compiler;
  2508. }
  2509. let _resolver;
  2510. /**
  2511. * Register the message resolver
  2512. *
  2513. * @param resolver - A {@link MessageResolver} function
  2514. *
  2515. * @VueI18nGeneral
  2516. */
  2517. function registerMessageResolver(resolver) {
  2518. _resolver = resolver;
  2519. }
  2520. let _fallbacker;
  2521. /**
  2522. * Register the locale fallbacker
  2523. *
  2524. * @param fallbacker - A {@link LocaleFallbacker} function
  2525. *
  2526. * @VueI18nGeneral
  2527. */
  2528. function registerLocaleFallbacker(fallbacker) {
  2529. _fallbacker = fallbacker;
  2530. }
  2531. // Additional Meta for Intlify DevTools
  2532. let _additionalMeta = null;
  2533. /* #__NO_SIDE_EFFECTS__ */
  2534. const setAdditionalMeta = (meta) => {
  2535. _additionalMeta = meta;
  2536. };
  2537. /* #__NO_SIDE_EFFECTS__ */
  2538. const getAdditionalMeta = () => _additionalMeta;
  2539. let _fallbackContext = null;
  2540. const setFallbackContext = (context) => {
  2541. _fallbackContext = context;
  2542. };
  2543. const getFallbackContext = () => _fallbackContext;
  2544. // ID for CoreContext
  2545. let _cid = 0;
  2546. function createCoreContext(options = {}) {
  2547. // setup options
  2548. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  2549. const version = isString(options.version) ? options.version : VERSION;
  2550. const locale = isString(options.locale) || isFunction(options.locale)
  2551. ? options.locale
  2552. : DEFAULT_LOCALE;
  2553. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  2554. const fallbackLocale = isArray(options.fallbackLocale) ||
  2555. isPlainObject(options.fallbackLocale) ||
  2556. isString(options.fallbackLocale) ||
  2557. options.fallbackLocale === false
  2558. ? options.fallbackLocale
  2559. : _locale;
  2560. const messages = isPlainObject(options.messages)
  2561. ? options.messages
  2562. : createResources(_locale);
  2563. const datetimeFormats = isPlainObject(options.datetimeFormats)
  2564. ? options.datetimeFormats
  2565. : createResources(_locale)
  2566. ;
  2567. const numberFormats = isPlainObject(options.numberFormats)
  2568. ? options.numberFormats
  2569. : createResources(_locale)
  2570. ;
  2571. const modifiers = assign(create(), options.modifiers, getDefaultLinkedModifiers());
  2572. const pluralRules = options.pluralRules || create();
  2573. const missing = isFunction(options.missing) ? options.missing : null;
  2574. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2575. ? options.missingWarn
  2576. : true;
  2577. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2578. ? options.fallbackWarn
  2579. : true;
  2580. const fallbackFormat = !!options.fallbackFormat;
  2581. const unresolving = !!options.unresolving;
  2582. const postTranslation = isFunction(options.postTranslation)
  2583. ? options.postTranslation
  2584. : null;
  2585. const processor = isPlainObject(options.processor) ? options.processor : null;
  2586. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2587. ? options.warnHtmlMessage
  2588. : true;
  2589. const escapeParameter = !!options.escapeParameter;
  2590. const messageCompiler = isFunction(options.messageCompiler)
  2591. ? options.messageCompiler
  2592. : _compiler;
  2593. const messageResolver = isFunction(options.messageResolver)
  2594. ? options.messageResolver
  2595. : _resolver || resolveWithKeyValue;
  2596. const localeFallbacker = isFunction(options.localeFallbacker)
  2597. ? options.localeFallbacker
  2598. : _fallbacker || fallbackWithSimple;
  2599. const fallbackContext = isObject(options.fallbackContext)
  2600. ? options.fallbackContext
  2601. : undefined;
  2602. // setup internal options
  2603. const internalOptions = options;
  2604. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  2605. ? internalOptions.__datetimeFormatters
  2606. : new Map()
  2607. ;
  2608. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  2609. ? internalOptions.__numberFormatters
  2610. : new Map()
  2611. ;
  2612. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  2613. _cid++;
  2614. const context = {
  2615. version,
  2616. cid: _cid,
  2617. locale,
  2618. fallbackLocale,
  2619. messages,
  2620. modifiers,
  2621. pluralRules,
  2622. missing,
  2623. missingWarn,
  2624. fallbackWarn,
  2625. fallbackFormat,
  2626. unresolving,
  2627. postTranslation,
  2628. processor,
  2629. warnHtmlMessage,
  2630. escapeParameter,
  2631. messageCompiler,
  2632. messageResolver,
  2633. localeFallbacker,
  2634. fallbackContext,
  2635. onWarn,
  2636. __meta
  2637. };
  2638. {
  2639. context.datetimeFormats = datetimeFormats;
  2640. context.numberFormats = numberFormats;
  2641. context.__datetimeFormatters = __datetimeFormatters;
  2642. context.__numberFormatters = __numberFormatters;
  2643. }
  2644. // for vue-devtools timeline event
  2645. {
  2646. context.__v_emitter =
  2647. internalOptions.__v_emitter != null
  2648. ? internalOptions.__v_emitter
  2649. : undefined;
  2650. }
  2651. // NOTE: experimental !!
  2652. {
  2653. initI18nDevTools(context, version, __meta);
  2654. }
  2655. return context;
  2656. }
  2657. const createResources = (locale) => ({ [locale]: create() });
  2658. /** @internal */
  2659. function isTranslateFallbackWarn(fallback, key) {
  2660. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2661. }
  2662. /** @internal */
  2663. function isTranslateMissingWarn(missing, key) {
  2664. return missing instanceof RegExp ? missing.test(key) : missing;
  2665. }
  2666. /** @internal */
  2667. function handleMissing(context, key, locale, missingWarn, type) {
  2668. const { missing, onWarn } = context;
  2669. // for vue-devtools timeline event
  2670. {
  2671. const emitter = context.__v_emitter;
  2672. if (emitter) {
  2673. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  2674. locale,
  2675. key,
  2676. type,
  2677. groupId: `${type}:${key}`
  2678. });
  2679. }
  2680. }
  2681. if (missing !== null) {
  2682. const ret = missing(context, locale, key, type);
  2683. return isString(ret) ? ret : key;
  2684. }
  2685. else {
  2686. if (isTranslateMissingWarn(missingWarn, key)) {
  2687. onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  2688. }
  2689. return key;
  2690. }
  2691. }
  2692. /** @internal */
  2693. function updateFallbackLocale(ctx, locale, fallback) {
  2694. const context = ctx;
  2695. context.__localeChainCache = new Map();
  2696. ctx.localeFallbacker(ctx, fallback, locale);
  2697. }
  2698. /** @internal */
  2699. function isAlmostSameLocale(locale, compareLocale) {
  2700. if (locale === compareLocale)
  2701. return false;
  2702. return locale.split('-')[0] === compareLocale.split('-')[0];
  2703. }
  2704. /** @internal */
  2705. function isImplicitFallback(targetLocale, locales) {
  2706. const index = locales.indexOf(targetLocale);
  2707. if (index === -1) {
  2708. return false;
  2709. }
  2710. for (let i = index + 1; i < locales.length; i++) {
  2711. if (isAlmostSameLocale(targetLocale, locales[i])) {
  2712. return true;
  2713. }
  2714. }
  2715. return false;
  2716. }
  2717. /* eslint-enable @typescript-eslint/no-explicit-any */
  2718. function format(ast) {
  2719. const msg = (ctx) => formatParts(ctx, ast);
  2720. return msg;
  2721. }
  2722. function formatParts(ctx, ast) {
  2723. const body = resolveBody(ast);
  2724. if (body == null) {
  2725. throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
  2726. }
  2727. const type = resolveType(body);
  2728. if (type === 1 /* NodeTypes.Plural */) {
  2729. const plural = body;
  2730. const cases = resolveCases(plural);
  2731. return ctx.plural(cases.reduce((messages, c) => [
  2732. ...messages,
  2733. formatMessageParts(ctx, c)
  2734. ], []));
  2735. }
  2736. else {
  2737. return formatMessageParts(ctx, body);
  2738. }
  2739. }
  2740. function formatMessageParts(ctx, node) {
  2741. const static_ = resolveStatic(node);
  2742. if (static_ != null) {
  2743. return ctx.type === 'text'
  2744. ? static_
  2745. : ctx.normalize([static_]);
  2746. }
  2747. else {
  2748. const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  2749. return ctx.normalize(messages);
  2750. }
  2751. }
  2752. function formatMessagePart(ctx, node) {
  2753. const type = resolveType(node);
  2754. switch (type) {
  2755. case 3 /* NodeTypes.Text */: {
  2756. return resolveValue$1(node, type);
  2757. }
  2758. case 9 /* NodeTypes.Literal */: {
  2759. return resolveValue$1(node, type);
  2760. }
  2761. case 4 /* NodeTypes.Named */: {
  2762. const named = node;
  2763. if (hasOwn(named, 'k') && named.k) {
  2764. return ctx.interpolate(ctx.named(named.k));
  2765. }
  2766. if (hasOwn(named, 'key') && named.key) {
  2767. return ctx.interpolate(ctx.named(named.key));
  2768. }
  2769. throw createUnhandleNodeError(type);
  2770. }
  2771. case 5 /* NodeTypes.List */: {
  2772. const list = node;
  2773. if (hasOwn(list, 'i') && isNumber(list.i)) {
  2774. return ctx.interpolate(ctx.list(list.i));
  2775. }
  2776. if (hasOwn(list, 'index') && isNumber(list.index)) {
  2777. return ctx.interpolate(ctx.list(list.index));
  2778. }
  2779. throw createUnhandleNodeError(type);
  2780. }
  2781. case 6 /* NodeTypes.Linked */: {
  2782. const linked = node;
  2783. const modifier = resolveLinkedModifier(linked);
  2784. const key = resolveLinkedKey(linked);
  2785. return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  2786. }
  2787. case 7 /* NodeTypes.LinkedKey */: {
  2788. return resolveValue$1(node, type);
  2789. }
  2790. case 8 /* NodeTypes.LinkedModifier */: {
  2791. return resolveValue$1(node, type);
  2792. }
  2793. default:
  2794. throw new Error(`unhandled node on format message part: ${type}`);
  2795. }
  2796. }
  2797. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  2798. function checkHtmlMessage(source, warnHtmlMessage) {
  2799. if (warnHtmlMessage && detectHtmlTag(source)) {
  2800. warn(format$1(WARN_MESSAGE, { source }));
  2801. }
  2802. }
  2803. const defaultOnCacheKey = (message) => message;
  2804. let compileCache = create();
  2805. function onCompileWarn(_warn) {
  2806. if (_warn.code === CompileWarnCodes.USE_MODULO_SYNTAX) {
  2807. warn(`The use of named interpolation with modulo syntax is deprecated. ` +
  2808. `It will be removed in v10.\n` +
  2809. `reference: https://vue-i18n.intlify.dev/guide/essentials/syntax#rails-i18n-format \n` +
  2810. `(message compiler warning message: ${_warn.message})`);
  2811. }
  2812. }
  2813. function clearCompileCache() {
  2814. compileCache = create();
  2815. }
  2816. function baseCompile(message, options = {}) {
  2817. // error detecting on compile
  2818. let detectError = false;
  2819. const onError = options.onError || defaultOnError;
  2820. options.onError = (err) => {
  2821. detectError = true;
  2822. onError(err);
  2823. };
  2824. // compile with mesasge-compiler
  2825. return { ...baseCompile$1(message, options), detectError };
  2826. }
  2827. /* #__NO_SIDE_EFFECTS__ */
  2828. const compileToFunction = (message, context) => {
  2829. if (!isString(message)) {
  2830. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
  2831. }
  2832. // set onWarn
  2833. {
  2834. context.onWarn = onCompileWarn;
  2835. }
  2836. {
  2837. // check HTML message
  2838. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  2839. ? context.warnHtmlMessage
  2840. : true;
  2841. checkHtmlMessage(message, warnHtmlMessage);
  2842. // check caches
  2843. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  2844. const cacheKey = onCacheKey(message);
  2845. const cached = compileCache[cacheKey];
  2846. if (cached) {
  2847. return cached;
  2848. }
  2849. // compile
  2850. const { code, detectError } = baseCompile(message, context);
  2851. // evaluate function
  2852. const msg = new Function(`return ${code}`)();
  2853. // if occurred compile error, don't cache
  2854. return !detectError
  2855. ? (compileCache[cacheKey] = msg)
  2856. : msg;
  2857. }
  2858. };
  2859. function compile(message, context) {
  2860. // set onWarn
  2861. {
  2862. context.onWarn = onCompileWarn;
  2863. }
  2864. if (isString(message)) {
  2865. // check HTML message
  2866. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  2867. ? context.warnHtmlMessage
  2868. : true;
  2869. checkHtmlMessage(message, warnHtmlMessage);
  2870. // check caches
  2871. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  2872. const cacheKey = onCacheKey(message);
  2873. const cached = compileCache[cacheKey];
  2874. if (cached) {
  2875. return cached;
  2876. }
  2877. // compile with JIT mode
  2878. const { ast, detectError } = baseCompile(message, {
  2879. ...context,
  2880. location: true,
  2881. jit: true
  2882. });
  2883. // compose message function from AST
  2884. const msg = format(ast);
  2885. // if occurred compile error, don't cache
  2886. return !detectError
  2887. ? (compileCache[cacheKey] = msg)
  2888. : msg;
  2889. }
  2890. else {
  2891. if (!isMessageAST(message)) {
  2892. warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  2893. return (() => message);
  2894. }
  2895. // AST case (passed from bundler)
  2896. const cacheKey = message.cacheKey;
  2897. if (cacheKey) {
  2898. const cached = compileCache[cacheKey];
  2899. if (cached) {
  2900. return cached;
  2901. }
  2902. // compose message function from message (AST)
  2903. return (compileCache[cacheKey] =
  2904. format(message));
  2905. }
  2906. else {
  2907. return format(message);
  2908. }
  2909. }
  2910. }
  2911. const NOOP_MESSAGE_FUNCTION = () => '';
  2912. const isMessageFunction = (val) => isFunction(val);
  2913. // implementation of `translate` function
  2914. function translate(context, ...args) {
  2915. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  2916. const [key, options] = parseTranslateArgs(...args);
  2917. const missingWarn = isBoolean(options.missingWarn)
  2918. ? options.missingWarn
  2919. : context.missingWarn;
  2920. const fallbackWarn = isBoolean(options.fallbackWarn)
  2921. ? options.fallbackWarn
  2922. : context.fallbackWarn;
  2923. const escapeParameter = isBoolean(options.escapeParameter)
  2924. ? options.escapeParameter
  2925. : context.escapeParameter;
  2926. const resolvedMessage = !!options.resolvedMessage;
  2927. // prettier-ignore
  2928. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  2929. ? !isBoolean(options.default)
  2930. ? options.default
  2931. : (!messageCompiler ? () => key : key)
  2932. : fallbackFormat // default by `fallbackFormat` option
  2933. ? (!messageCompiler ? () => key : key)
  2934. : '';
  2935. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  2936. const locale = getLocale(context, options);
  2937. // escape params
  2938. escapeParameter && escapeParams(options);
  2939. // resolve message format
  2940. // eslint-disable-next-line prefer-const
  2941. let [formatScope, targetLocale, message] = !resolvedMessage
  2942. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  2943. : [
  2944. key,
  2945. locale,
  2946. messages[locale] || create()
  2947. ];
  2948. // NOTE:
  2949. // Fix to work around `ssrTransfrom` bug in Vite.
  2950. // https://github.com/vitejs/vite/issues/4306
  2951. // To get around this, use temporary variables.
  2952. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  2953. let format = formatScope;
  2954. // if you use default message, set it as message format!
  2955. let cacheBaseKey = key;
  2956. if (!resolvedMessage &&
  2957. !(isString(format) ||
  2958. isMessageAST(format) ||
  2959. isMessageFunction(format))) {
  2960. if (enableDefaultMsg) {
  2961. format = defaultMsgOrKey;
  2962. cacheBaseKey = format;
  2963. }
  2964. }
  2965. // checking message format and target locale
  2966. if (!resolvedMessage &&
  2967. (!(isString(format) ||
  2968. isMessageAST(format) ||
  2969. isMessageFunction(format)) ||
  2970. !isString(targetLocale))) {
  2971. return unresolving ? NOT_REOSLVED : key;
  2972. }
  2973. // TODO: refactor
  2974. if (isString(format) && context.messageCompiler == null) {
  2975. warn(`The message format compilation is not supported in this build. ` +
  2976. `Because message compiler isn't included. ` +
  2977. `You need to pre-compilation all message format. ` +
  2978. `So translate function return '${key}'.`);
  2979. return key;
  2980. }
  2981. // setup compile error detecting
  2982. let occurred = false;
  2983. const onError = () => {
  2984. occurred = true;
  2985. };
  2986. // compile message format
  2987. const msg = !isMessageFunction(format)
  2988. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  2989. : format;
  2990. // if occurred compile error, return the message format
  2991. if (occurred) {
  2992. return format;
  2993. }
  2994. // evaluate message with context
  2995. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  2996. const msgContext = createMessageContext(ctxOptions);
  2997. const messaged = evaluateMessage(context, msg, msgContext);
  2998. // if use post translation option, proceed it with handler
  2999. let ret = postTranslation
  3000. ? postTranslation(messaged, key)
  3001. : messaged;
  3002. // apply HTML sanitization for security
  3003. if (escapeParameter && isString(ret)) {
  3004. ret = sanitizeTranslatedHtml(ret);
  3005. }
  3006. // NOTE: experimental !!
  3007. {
  3008. // prettier-ignore
  3009. const payloads = {
  3010. timestamp: Date.now(),
  3011. key: isString(key)
  3012. ? key
  3013. : isMessageFunction(format)
  3014. ? format.key
  3015. : '',
  3016. locale: targetLocale || (isMessageFunction(format)
  3017. ? format.locale
  3018. : ''),
  3019. format: isString(format)
  3020. ? format
  3021. : isMessageFunction(format)
  3022. ? format.source
  3023. : '',
  3024. message: ret
  3025. };
  3026. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  3027. translateDevTools(payloads);
  3028. }
  3029. return ret;
  3030. }
  3031. function escapeParams(options) {
  3032. if (isArray(options.list)) {
  3033. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  3034. }
  3035. else if (isObject(options.named)) {
  3036. Object.keys(options.named).forEach(key => {
  3037. if (isString(options.named[key])) {
  3038. options.named[key] = escapeHtml(options.named[key]);
  3039. }
  3040. });
  3041. }
  3042. }
  3043. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  3044. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  3045. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  3046. let message = create();
  3047. let targetLocale;
  3048. let format = null;
  3049. let from = locale;
  3050. let to = null;
  3051. const type = 'translate';
  3052. for (let i = 0; i < locales.length; i++) {
  3053. targetLocale = to = locales[i];
  3054. if (locale !== targetLocale &&
  3055. !isAlmostSameLocale(locale, targetLocale) &&
  3056. isTranslateFallbackWarn(fallbackWarn, key)) {
  3057. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  3058. key,
  3059. target: targetLocale
  3060. }));
  3061. }
  3062. // for vue-devtools timeline event
  3063. if (locale !== targetLocale) {
  3064. const emitter = context.__v_emitter;
  3065. if (emitter) {
  3066. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3067. type,
  3068. key,
  3069. from,
  3070. to,
  3071. groupId: `${type}:${key}`
  3072. });
  3073. }
  3074. }
  3075. message =
  3076. messages[targetLocale] || create();
  3077. // for vue-devtools timeline event
  3078. let start = null;
  3079. let startTag;
  3080. let endTag;
  3081. if (inBrowser) {
  3082. start = window.performance.now();
  3083. startTag = 'intlify-message-resolve-start';
  3084. endTag = 'intlify-message-resolve-end';
  3085. mark && mark(startTag);
  3086. }
  3087. if ((format = resolveValue(message, key)) === null) {
  3088. // if null, resolve with object key path
  3089. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  3090. }
  3091. // for vue-devtools timeline event
  3092. if (inBrowser) {
  3093. const end = window.performance.now();
  3094. const emitter = context.__v_emitter;
  3095. if (emitter && start && format) {
  3096. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  3097. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  3098. key,
  3099. message: format,
  3100. time: end - start,
  3101. groupId: `${type}:${key}`
  3102. });
  3103. }
  3104. if (startTag && endTag && mark && measure) {
  3105. mark(endTag);
  3106. measure('intlify message resolve', startTag, endTag);
  3107. }
  3108. }
  3109. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  3110. break;
  3111. }
  3112. if (!isImplicitFallback(targetLocale, locales)) {
  3113. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3114. key, targetLocale, missingWarn, type);
  3115. if (missingRet !== key) {
  3116. format = missingRet;
  3117. }
  3118. }
  3119. from = to;
  3120. }
  3121. return [format, targetLocale, message];
  3122. }
  3123. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  3124. const { messageCompiler, warnHtmlMessage } = context;
  3125. if (isMessageFunction(format)) {
  3126. const msg = format;
  3127. msg.locale = msg.locale || targetLocale;
  3128. msg.key = msg.key || key;
  3129. return msg;
  3130. }
  3131. if (messageCompiler == null) {
  3132. const msg = (() => format);
  3133. msg.locale = targetLocale;
  3134. msg.key = key;
  3135. return msg;
  3136. }
  3137. // for vue-devtools timeline event
  3138. let start = null;
  3139. let startTag;
  3140. let endTag;
  3141. if (inBrowser) {
  3142. start = window.performance.now();
  3143. startTag = 'intlify-message-compilation-start';
  3144. endTag = 'intlify-message-compilation-end';
  3145. mark && mark(startTag);
  3146. }
  3147. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  3148. // for vue-devtools timeline event
  3149. if (inBrowser) {
  3150. const end = window.performance.now();
  3151. const emitter = context.__v_emitter;
  3152. if (emitter && start) {
  3153. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  3154. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  3155. message: format,
  3156. time: end - start,
  3157. groupId: `${'translate'}:${key}`
  3158. });
  3159. }
  3160. if (startTag && endTag && mark && measure) {
  3161. mark(endTag);
  3162. measure('intlify message compilation', startTag, endTag);
  3163. }
  3164. }
  3165. msg.locale = targetLocale;
  3166. msg.key = key;
  3167. msg.source = format;
  3168. return msg;
  3169. }
  3170. function evaluateMessage(context, msg, msgCtx) {
  3171. // for vue-devtools timeline event
  3172. let start = null;
  3173. let startTag;
  3174. let endTag;
  3175. if (inBrowser) {
  3176. start = window.performance.now();
  3177. startTag = 'intlify-message-evaluation-start';
  3178. endTag = 'intlify-message-evaluation-end';
  3179. mark && mark(startTag);
  3180. }
  3181. const messaged = msg(msgCtx);
  3182. // for vue-devtools timeline event
  3183. if (inBrowser) {
  3184. const end = window.performance.now();
  3185. const emitter = context.__v_emitter;
  3186. if (emitter && start) {
  3187. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  3188. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  3189. value: messaged,
  3190. time: end - start,
  3191. groupId: `${'translate'}:${msg.key}`
  3192. });
  3193. }
  3194. if (startTag && endTag && mark && measure) {
  3195. mark(endTag);
  3196. measure('intlify message evaluation', startTag, endTag);
  3197. }
  3198. }
  3199. return messaged;
  3200. }
  3201. /** @internal */
  3202. function parseTranslateArgs(...args) {
  3203. const [arg1, arg2, arg3] = args;
  3204. const options = create();
  3205. if (!isString(arg1) &&
  3206. !isNumber(arg1) &&
  3207. !isMessageFunction(arg1) &&
  3208. !isMessageAST(arg1)) {
  3209. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3210. }
  3211. // prettier-ignore
  3212. const key = isNumber(arg1)
  3213. ? String(arg1)
  3214. : isMessageFunction(arg1)
  3215. ? arg1
  3216. : arg1;
  3217. if (isNumber(arg2)) {
  3218. options.plural = arg2;
  3219. }
  3220. else if (isString(arg2)) {
  3221. options.default = arg2;
  3222. }
  3223. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  3224. options.named = arg2;
  3225. }
  3226. else if (isArray(arg2)) {
  3227. options.list = arg2;
  3228. }
  3229. if (isNumber(arg3)) {
  3230. options.plural = arg3;
  3231. }
  3232. else if (isString(arg3)) {
  3233. options.default = arg3;
  3234. }
  3235. else if (isPlainObject(arg3)) {
  3236. assign(options, arg3);
  3237. }
  3238. return [key, options];
  3239. }
  3240. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  3241. return {
  3242. locale,
  3243. key,
  3244. warnHtmlMessage,
  3245. onError: (err) => {
  3246. onError && onError(err);
  3247. {
  3248. const _source = getSourceForCodeFrame(source);
  3249. const message = `Message compilation error: ${err.message}`;
  3250. const codeFrame = err.location &&
  3251. _source &&
  3252. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  3253. const emitter = context.__v_emitter;
  3254. if (emitter && _source) {
  3255. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  3256. message: _source,
  3257. error: err.message,
  3258. start: err.location && err.location.start.offset,
  3259. end: err.location && err.location.end.offset,
  3260. groupId: `${'translate'}:${key}`
  3261. });
  3262. }
  3263. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  3264. }
  3265. },
  3266. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  3267. };
  3268. }
  3269. function getSourceForCodeFrame(source) {
  3270. if (isString(source)) {
  3271. return source;
  3272. }
  3273. else {
  3274. if (source.loc && source.loc.source) {
  3275. return source.loc.source;
  3276. }
  3277. }
  3278. }
  3279. function getMessageContextOptions(context, locale, message, options) {
  3280. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  3281. const resolveMessage = (key) => {
  3282. let val = resolveValue(message, key);
  3283. // fallback to root context
  3284. if (val == null && fallbackContext) {
  3285. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  3286. val = resolveValue(message, key);
  3287. }
  3288. if (isString(val) || isMessageAST(val)) {
  3289. let occurred = false;
  3290. const onError = () => {
  3291. occurred = true;
  3292. };
  3293. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  3294. return !occurred
  3295. ? msg
  3296. : NOOP_MESSAGE_FUNCTION;
  3297. }
  3298. else if (isMessageFunction(val)) {
  3299. return val;
  3300. }
  3301. else {
  3302. // TODO: should be implemented warning message
  3303. return NOOP_MESSAGE_FUNCTION;
  3304. }
  3305. };
  3306. const ctxOptions = {
  3307. locale,
  3308. modifiers,
  3309. pluralRules,
  3310. messages: resolveMessage
  3311. };
  3312. if (context.processor) {
  3313. ctxOptions.processor = context.processor;
  3314. }
  3315. if (options.list) {
  3316. ctxOptions.list = options.list;
  3317. }
  3318. if (options.named) {
  3319. ctxOptions.named = options.named;
  3320. }
  3321. if (isNumber(options.plural)) {
  3322. ctxOptions.pluralIndex = options.plural;
  3323. }
  3324. return ctxOptions;
  3325. }
  3326. const intlDefined = typeof Intl !== 'undefined';
  3327. const Availabilities = {
  3328. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  3329. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  3330. };
  3331. // implementation of `datetime` function
  3332. function datetime(context, ...args) {
  3333. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3334. const { __datetimeFormatters } = context;
  3335. if (!Availabilities.dateTimeFormat) {
  3336. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
  3337. return MISSING_RESOLVE_VALUE;
  3338. }
  3339. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  3340. const missingWarn = isBoolean(options.missingWarn)
  3341. ? options.missingWarn
  3342. : context.missingWarn;
  3343. const fallbackWarn = isBoolean(options.fallbackWarn)
  3344. ? options.fallbackWarn
  3345. : context.fallbackWarn;
  3346. const part = !!options.part;
  3347. const locale = getLocale(context, options);
  3348. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3349. fallbackLocale, locale);
  3350. if (!isString(key) || key === '') {
  3351. return new Intl.DateTimeFormat(locale, overrides).format(value);
  3352. }
  3353. // resolve format
  3354. let datetimeFormat = {};
  3355. let targetLocale;
  3356. let format = null;
  3357. let from = locale;
  3358. let to = null;
  3359. const type = 'datetime format';
  3360. for (let i = 0; i < locales.length; i++) {
  3361. targetLocale = to = locales[i];
  3362. if (locale !== targetLocale &&
  3363. isTranslateFallbackWarn(fallbackWarn, key)) {
  3364. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  3365. key,
  3366. target: targetLocale
  3367. }));
  3368. }
  3369. // for vue-devtools timeline event
  3370. if (locale !== targetLocale) {
  3371. const emitter = context.__v_emitter;
  3372. if (emitter) {
  3373. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3374. type,
  3375. key,
  3376. from,
  3377. to,
  3378. groupId: `${type}:${key}`
  3379. });
  3380. }
  3381. }
  3382. datetimeFormat =
  3383. datetimeFormats[targetLocale] || {};
  3384. format = datetimeFormat[key];
  3385. if (isPlainObject(format))
  3386. break;
  3387. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3388. from = to;
  3389. }
  3390. // checking format and target locale
  3391. if (!isPlainObject(format) || !isString(targetLocale)) {
  3392. return unresolving ? NOT_REOSLVED : key;
  3393. }
  3394. let id = `${targetLocale}__${key}`;
  3395. if (!isEmptyObject(overrides)) {
  3396. id = `${id}__${JSON.stringify(overrides)}`;
  3397. }
  3398. let formatter = __datetimeFormatters.get(id);
  3399. if (!formatter) {
  3400. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  3401. __datetimeFormatters.set(id, formatter);
  3402. }
  3403. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3404. }
  3405. /** @internal */
  3406. const DATETIME_FORMAT_OPTIONS_KEYS = [
  3407. 'localeMatcher',
  3408. 'weekday',
  3409. 'era',
  3410. 'year',
  3411. 'month',
  3412. 'day',
  3413. 'hour',
  3414. 'minute',
  3415. 'second',
  3416. 'timeZoneName',
  3417. 'formatMatcher',
  3418. 'hour12',
  3419. 'timeZone',
  3420. 'dateStyle',
  3421. 'timeStyle',
  3422. 'calendar',
  3423. 'dayPeriod',
  3424. 'numberingSystem',
  3425. 'hourCycle',
  3426. 'fractionalSecondDigits'
  3427. ];
  3428. /** @internal */
  3429. function parseDateTimeArgs(...args) {
  3430. const [arg1, arg2, arg3, arg4] = args;
  3431. const options = create();
  3432. let overrides = create();
  3433. let value;
  3434. if (isString(arg1)) {
  3435. // Only allow ISO strings - other date formats are often supported,
  3436. // but may cause different results in different browsers.
  3437. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  3438. if (!matches) {
  3439. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3440. }
  3441. // Some browsers can not parse the iso datetime separated by space,
  3442. // this is a compromise solution by replace the 'T'/' ' with 'T'
  3443. const dateTime = matches[3]
  3444. ? matches[3].trim().startsWith('T')
  3445. ? `${matches[1].trim()}${matches[3].trim()}`
  3446. : `${matches[1].trim()}T${matches[3].trim()}`
  3447. : matches[1].trim();
  3448. value = new Date(dateTime);
  3449. try {
  3450. // This will fail if the date is not valid
  3451. value.toISOString();
  3452. }
  3453. catch (e) {
  3454. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3455. }
  3456. }
  3457. else if (isDate(arg1)) {
  3458. if (isNaN(arg1.getTime())) {
  3459. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  3460. }
  3461. value = arg1;
  3462. }
  3463. else if (isNumber(arg1)) {
  3464. value = arg1;
  3465. }
  3466. else {
  3467. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3468. }
  3469. if (isString(arg2)) {
  3470. options.key = arg2;
  3471. }
  3472. else if (isPlainObject(arg2)) {
  3473. Object.keys(arg2).forEach(key => {
  3474. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  3475. overrides[key] = arg2[key];
  3476. }
  3477. else {
  3478. options[key] = arg2[key];
  3479. }
  3480. });
  3481. }
  3482. if (isString(arg3)) {
  3483. options.locale = arg3;
  3484. }
  3485. else if (isPlainObject(arg3)) {
  3486. overrides = arg3;
  3487. }
  3488. if (isPlainObject(arg4)) {
  3489. overrides = arg4;
  3490. }
  3491. return [options.key || '', value, options, overrides];
  3492. }
  3493. /** @internal */
  3494. function clearDateTimeFormat(ctx, locale, format) {
  3495. const context = ctx;
  3496. for (const key in format) {
  3497. const id = `${locale}__${key}`;
  3498. if (!context.__datetimeFormatters.has(id)) {
  3499. continue;
  3500. }
  3501. context.__datetimeFormatters.delete(id);
  3502. }
  3503. }
  3504. // implementation of `number` function
  3505. function number(context, ...args) {
  3506. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3507. const { __numberFormatters } = context;
  3508. if (!Availabilities.numberFormat) {
  3509. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  3510. return MISSING_RESOLVE_VALUE;
  3511. }
  3512. const [key, value, options, overrides] = parseNumberArgs(...args);
  3513. const missingWarn = isBoolean(options.missingWarn)
  3514. ? options.missingWarn
  3515. : context.missingWarn;
  3516. const fallbackWarn = isBoolean(options.fallbackWarn)
  3517. ? options.fallbackWarn
  3518. : context.fallbackWarn;
  3519. const part = !!options.part;
  3520. const locale = getLocale(context, options);
  3521. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3522. fallbackLocale, locale);
  3523. if (!isString(key) || key === '') {
  3524. return new Intl.NumberFormat(locale, overrides).format(value);
  3525. }
  3526. // resolve format
  3527. let numberFormat = {};
  3528. let targetLocale;
  3529. let format = null;
  3530. let from = locale;
  3531. let to = null;
  3532. const type = 'number format';
  3533. for (let i = 0; i < locales.length; i++) {
  3534. targetLocale = to = locales[i];
  3535. if (locale !== targetLocale &&
  3536. isTranslateFallbackWarn(fallbackWarn, key)) {
  3537. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  3538. key,
  3539. target: targetLocale
  3540. }));
  3541. }
  3542. // for vue-devtools timeline event
  3543. if (locale !== targetLocale) {
  3544. const emitter = context.__v_emitter;
  3545. if (emitter) {
  3546. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3547. type,
  3548. key,
  3549. from,
  3550. to,
  3551. groupId: `${type}:${key}`
  3552. });
  3553. }
  3554. }
  3555. numberFormat =
  3556. numberFormats[targetLocale] || {};
  3557. format = numberFormat[key];
  3558. if (isPlainObject(format))
  3559. break;
  3560. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3561. from = to;
  3562. }
  3563. // checking format and target locale
  3564. if (!isPlainObject(format) || !isString(targetLocale)) {
  3565. return unresolving ? NOT_REOSLVED : key;
  3566. }
  3567. let id = `${targetLocale}__${key}`;
  3568. if (!isEmptyObject(overrides)) {
  3569. id = `${id}__${JSON.stringify(overrides)}`;
  3570. }
  3571. let formatter = __numberFormatters.get(id);
  3572. if (!formatter) {
  3573. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  3574. __numberFormatters.set(id, formatter);
  3575. }
  3576. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3577. }
  3578. /** @internal */
  3579. const NUMBER_FORMAT_OPTIONS_KEYS = [
  3580. 'localeMatcher',
  3581. 'style',
  3582. 'currency',
  3583. 'currencyDisplay',
  3584. 'currencySign',
  3585. 'useGrouping',
  3586. 'minimumIntegerDigits',
  3587. 'minimumFractionDigits',
  3588. 'maximumFractionDigits',
  3589. 'minimumSignificantDigits',
  3590. 'maximumSignificantDigits',
  3591. 'compactDisplay',
  3592. 'notation',
  3593. 'signDisplay',
  3594. 'unit',
  3595. 'unitDisplay',
  3596. 'roundingMode',
  3597. 'roundingPriority',
  3598. 'roundingIncrement',
  3599. 'trailingZeroDisplay'
  3600. ];
  3601. /** @internal */
  3602. function parseNumberArgs(...args) {
  3603. const [arg1, arg2, arg3, arg4] = args;
  3604. const options = create();
  3605. let overrides = create();
  3606. if (!isNumber(arg1)) {
  3607. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3608. }
  3609. const value = arg1;
  3610. if (isString(arg2)) {
  3611. options.key = arg2;
  3612. }
  3613. else if (isPlainObject(arg2)) {
  3614. Object.keys(arg2).forEach(key => {
  3615. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  3616. overrides[key] = arg2[key];
  3617. }
  3618. else {
  3619. options[key] = arg2[key];
  3620. }
  3621. });
  3622. }
  3623. if (isString(arg3)) {
  3624. options.locale = arg3;
  3625. }
  3626. else if (isPlainObject(arg3)) {
  3627. overrides = arg3;
  3628. }
  3629. if (isPlainObject(arg4)) {
  3630. overrides = arg4;
  3631. }
  3632. return [options.key || '', value, options, overrides];
  3633. }
  3634. /** @internal */
  3635. function clearNumberFormat(ctx, locale, format) {
  3636. const context = ctx;
  3637. for (const key in format) {
  3638. const id = `${locale}__${key}`;
  3639. if (!context.__numberFormatters.has(id)) {
  3640. continue;
  3641. }
  3642. context.__numberFormatters.delete(id);
  3643. }
  3644. }
  3645. exports.AST_NODE_PROPS_KEYS = AST_NODE_PROPS_KEYS;
  3646. exports.CompileErrorCodes = CompileErrorCodes;
  3647. exports.CoreErrorCodes = CoreErrorCodes;
  3648. exports.CoreWarnCodes = CoreWarnCodes;
  3649. exports.DATETIME_FORMAT_OPTIONS_KEYS = DATETIME_FORMAT_OPTIONS_KEYS;
  3650. exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
  3651. exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
  3652. exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
  3653. exports.NOT_REOSLVED = NOT_REOSLVED;
  3654. exports.NUMBER_FORMAT_OPTIONS_KEYS = NUMBER_FORMAT_OPTIONS_KEYS;
  3655. exports.VERSION = VERSION;
  3656. exports.clearCompileCache = clearCompileCache;
  3657. exports.clearDateTimeFormat = clearDateTimeFormat;
  3658. exports.clearNumberFormat = clearNumberFormat;
  3659. exports.compile = compile;
  3660. exports.compileToFunction = compileToFunction;
  3661. exports.createCompileError = createCompileError;
  3662. exports.createCoreContext = createCoreContext;
  3663. exports.createCoreError = createCoreError;
  3664. exports.createMessageContext = createMessageContext;
  3665. exports.datetime = datetime;
  3666. exports.fallbackWithLocaleChain = fallbackWithLocaleChain;
  3667. exports.fallbackWithSimple = fallbackWithSimple;
  3668. exports.getAdditionalMeta = getAdditionalMeta;
  3669. exports.getDevToolsHook = getDevToolsHook;
  3670. exports.getFallbackContext = getFallbackContext;
  3671. exports.getLocale = getLocale;
  3672. exports.getWarnMessage = getWarnMessage;
  3673. exports.handleMissing = handleMissing;
  3674. exports.initI18nDevTools = initI18nDevTools;
  3675. exports.isAlmostSameLocale = isAlmostSameLocale;
  3676. exports.isImplicitFallback = isImplicitFallback;
  3677. exports.isMessageAST = isMessageAST;
  3678. exports.isMessageFunction = isMessageFunction;
  3679. exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
  3680. exports.isTranslateMissingWarn = isTranslateMissingWarn;
  3681. exports.number = number;
  3682. exports.parse = parse;
  3683. exports.parseDateTimeArgs = parseDateTimeArgs;
  3684. exports.parseNumberArgs = parseNumberArgs;
  3685. exports.parseTranslateArgs = parseTranslateArgs;
  3686. exports.registerLocaleFallbacker = registerLocaleFallbacker;
  3687. exports.registerMessageCompiler = registerMessageCompiler;
  3688. exports.registerMessageResolver = registerMessageResolver;
  3689. exports.resolveLocale = resolveLocale;
  3690. exports.resolveValue = resolveValue;
  3691. exports.resolveWithKeyValue = resolveWithKeyValue;
  3692. exports.setAdditionalMeta = setAdditionalMeta;
  3693. exports.setDevToolsHook = setDevToolsHook;
  3694. exports.setFallbackContext = setFallbackContext;
  3695. exports.translate = translate;
  3696. exports.translateDevTools = translateDevTools;
  3697. exports.updateFallbackLocale = updateFallbackLocale;
  3698. return exports;
  3699. })({});