core-base.esm-browser.js 119 KB

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