c1d8ccb64427487e69fd154ad4b6771847409bd2f136f617189e36fc2b228c9173c68e47d4715c67e5d142475703d90b791b2a06c3610208907e4678e38e4b 128 KB

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