core-base.global.js 129 KB

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