core-base.esm-browser.js 118 KB

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