b94d418540250cd074f79495add5f8290e189b6c8d43a13fb231f77034ad3242a001febb1926146d69f02f7093b469fa441eb5687198a6f01ea962d3d46a4e 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956
  1. /*!
  2. * core-base v9.14.5
  3. * (c) 2025 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. 'use strict';
  7. var messageCompiler = require('@intlify/message-compiler');
  8. var shared = require('@intlify/shared');
  9. function isMessageAST(val) {
  10. return (shared.isObject(val) &&
  11. resolveType(val) === 0 &&
  12. (shared.hasOwn(val, 'b') || shared.hasOwn(val, 'body')));
  13. }
  14. const PROPS_BODY = ['b', 'body'];
  15. function resolveBody(node) {
  16. return resolveProps(node, PROPS_BODY);
  17. }
  18. const PROPS_CASES = ['c', 'cases'];
  19. function resolveCases(node) {
  20. return resolveProps(node, PROPS_CASES, []);
  21. }
  22. const PROPS_STATIC = ['s', 'static'];
  23. function resolveStatic(node) {
  24. return resolveProps(node, PROPS_STATIC);
  25. }
  26. const PROPS_ITEMS = ['i', 'items'];
  27. function resolveItems(node) {
  28. return resolveProps(node, PROPS_ITEMS, []);
  29. }
  30. const PROPS_TYPE = ['t', 'type'];
  31. function resolveType(node) {
  32. return resolveProps(node, PROPS_TYPE);
  33. }
  34. const PROPS_VALUE = ['v', 'value'];
  35. function resolveValue$1(node, type) {
  36. const resolved = resolveProps(node, PROPS_VALUE);
  37. if (resolved != null) {
  38. return resolved;
  39. }
  40. else {
  41. throw createUnhandleNodeError(type);
  42. }
  43. }
  44. const PROPS_MODIFIER = ['m', 'modifier'];
  45. function resolveLinkedModifier(node) {
  46. return resolveProps(node, PROPS_MODIFIER);
  47. }
  48. const PROPS_KEY = ['k', 'key'];
  49. function resolveLinkedKey(node) {
  50. const resolved = resolveProps(node, PROPS_KEY);
  51. if (resolved) {
  52. return resolved;
  53. }
  54. else {
  55. throw createUnhandleNodeError(6 /* NodeTypes.Linked */);
  56. }
  57. }
  58. function resolveProps(node, props, defaultValue) {
  59. for (let i = 0; i < props.length; i++) {
  60. const prop = props[i];
  61. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  62. if (shared.hasOwn(node, prop) && node[prop] != null) {
  63. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  64. return node[prop];
  65. }
  66. }
  67. return defaultValue;
  68. }
  69. const AST_NODE_PROPS_KEYS = [
  70. ...PROPS_BODY,
  71. ...PROPS_CASES,
  72. ...PROPS_STATIC,
  73. ...PROPS_ITEMS,
  74. ...PROPS_KEY,
  75. ...PROPS_MODIFIER,
  76. ...PROPS_VALUE,
  77. ...PROPS_TYPE
  78. ];
  79. function createUnhandleNodeError(type) {
  80. return new Error(`unhandled node type: ${type}`);
  81. }
  82. const pathStateMachine = [];
  83. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  84. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  85. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  86. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  87. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  88. };
  89. pathStateMachine[1 /* States.IN_PATH */] = {
  90. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  91. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  92. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  93. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  94. };
  95. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  96. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  97. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  98. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  99. };
  100. pathStateMachine[3 /* States.IN_IDENT */] = {
  101. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  102. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  103. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  104. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  105. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  106. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  107. };
  108. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  109. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  110. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  111. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  112. 4 /* States.IN_SUB_PATH */,
  113. 2 /* Actions.INC_SUB_PATH_DEPTH */
  114. ],
  115. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  116. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  117. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  118. };
  119. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  120. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  121. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  122. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  123. };
  124. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  125. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  126. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  127. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  128. };
  129. /**
  130. * Check if an expression is a literal value.
  131. */
  132. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  133. function isLiteral(exp) {
  134. return literalValueRE.test(exp);
  135. }
  136. /**
  137. * Strip quotes from a string
  138. */
  139. function stripQuotes(str) {
  140. const a = str.charCodeAt(0);
  141. const b = str.charCodeAt(str.length - 1);
  142. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  143. }
  144. /**
  145. * Determine the type of a character in a keypath.
  146. */
  147. function getPathCharType(ch) {
  148. if (ch === undefined || ch === null) {
  149. return "o" /* PathCharTypes.END_OF_FAIL */;
  150. }
  151. const code = ch.charCodeAt(0);
  152. switch (code) {
  153. case 0x5b: // [
  154. case 0x5d: // ]
  155. case 0x2e: // .
  156. case 0x22: // "
  157. case 0x27: // '
  158. return ch;
  159. case 0x5f: // _
  160. case 0x24: // $
  161. case 0x2d: // -
  162. return "i" /* PathCharTypes.IDENT */;
  163. case 0x09: // Tab (HT)
  164. case 0x0a: // Newline (LF)
  165. case 0x0d: // Return (CR)
  166. case 0xa0: // No-break space (NBSP)
  167. case 0xfeff: // Byte Order Mark (BOM)
  168. case 0x2028: // Line Separator (LS)
  169. case 0x2029: // Paragraph Separator (PS)
  170. return "w" /* PathCharTypes.WORKSPACE */;
  171. }
  172. return "i" /* PathCharTypes.IDENT */;
  173. }
  174. /**
  175. * Format a subPath, return its plain form if it is
  176. * a literal string or number. Otherwise prepend the
  177. * dynamic indicator (*).
  178. */
  179. function formatSubPath(path) {
  180. const trimmed = path.trim();
  181. // invalid leading 0
  182. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  183. return false;
  184. }
  185. return isLiteral(trimmed)
  186. ? stripQuotes(trimmed)
  187. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  188. }
  189. /**
  190. * Parse a string path into an array of segments
  191. */
  192. function parse(path) {
  193. const keys = [];
  194. let index = -1;
  195. let mode = 0 /* States.BEFORE_PATH */;
  196. let subPathDepth = 0;
  197. let c;
  198. let key; // eslint-disable-line
  199. let newChar;
  200. let type;
  201. let transition;
  202. let action;
  203. let typeMap;
  204. const actions = [];
  205. actions[0 /* Actions.APPEND */] = () => {
  206. if (key === undefined) {
  207. key = newChar;
  208. }
  209. else {
  210. key += newChar;
  211. }
  212. };
  213. actions[1 /* Actions.PUSH */] = () => {
  214. if (key !== undefined) {
  215. keys.push(key);
  216. key = undefined;
  217. }
  218. };
  219. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  220. actions[0 /* Actions.APPEND */]();
  221. subPathDepth++;
  222. };
  223. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  224. if (subPathDepth > 0) {
  225. subPathDepth--;
  226. mode = 4 /* States.IN_SUB_PATH */;
  227. actions[0 /* Actions.APPEND */]();
  228. }
  229. else {
  230. subPathDepth = 0;
  231. if (key === undefined) {
  232. return false;
  233. }
  234. key = formatSubPath(key);
  235. if (key === false) {
  236. return false;
  237. }
  238. else {
  239. actions[1 /* Actions.PUSH */]();
  240. }
  241. }
  242. };
  243. function maybeUnescapeQuote() {
  244. const nextChar = path[index + 1];
  245. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  246. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  247. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  248. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  249. index++;
  250. newChar = '\\' + nextChar;
  251. actions[0 /* Actions.APPEND */]();
  252. return true;
  253. }
  254. }
  255. while (mode !== null) {
  256. index++;
  257. c = path[index];
  258. if (c === '\\' && maybeUnescapeQuote()) {
  259. continue;
  260. }
  261. type = getPathCharType(c);
  262. typeMap = pathStateMachine[mode];
  263. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  264. // check parse error
  265. if (transition === 8 /* States.ERROR */) {
  266. return;
  267. }
  268. mode = transition[0];
  269. if (transition[1] !== undefined) {
  270. action = actions[transition[1]];
  271. if (action) {
  272. newChar = c;
  273. if (action() === false) {
  274. return;
  275. }
  276. }
  277. }
  278. // check parse finish
  279. if (mode === 7 /* States.AFTER_PATH */) {
  280. return keys;
  281. }
  282. }
  283. }
  284. // path token cache
  285. const cache = new Map();
  286. /**
  287. * key-value message resolver
  288. *
  289. * @remarks
  290. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  291. *
  292. * @param obj - A target object to be resolved with path
  293. * @param path - A {@link Path | path} to resolve the value of message
  294. *
  295. * @returns A resolved {@link PathValue | path value}
  296. *
  297. * @VueI18nGeneral
  298. */
  299. function resolveWithKeyValue(obj, path) {
  300. return shared.isObject(obj) ? obj[path] : null;
  301. }
  302. /**
  303. * message resolver
  304. *
  305. * @remarks
  306. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  307. *
  308. * @param obj - A target object to be resolved with path
  309. * @param path - A {@link Path | path} to resolve the value of message
  310. *
  311. * @returns A resolved {@link PathValue | path value}
  312. *
  313. * @VueI18nGeneral
  314. */
  315. function resolveValue(obj, path) {
  316. // check object
  317. if (!shared.isObject(obj)) {
  318. return null;
  319. }
  320. // parse path
  321. let hit = cache.get(path);
  322. if (!hit) {
  323. hit = parse(path);
  324. if (hit) {
  325. cache.set(path, hit);
  326. }
  327. }
  328. // check hit
  329. if (!hit) {
  330. return null;
  331. }
  332. // resolve path value
  333. const len = hit.length;
  334. let last = obj;
  335. let i = 0;
  336. while (i < len) {
  337. const key = hit[i];
  338. /**
  339. * NOTE:
  340. * if `key` is intlify message format AST node key and `last` is intlify message format AST, skip it.
  341. * because the AST node is not a key-value structure.
  342. */
  343. if (AST_NODE_PROPS_KEYS.includes(key) && isMessageAST(last)) {
  344. return null;
  345. }
  346. const val = last[key];
  347. if (val === undefined) {
  348. return null;
  349. }
  350. if (shared.isFunction(last)) {
  351. return null;
  352. }
  353. last = val;
  354. i++;
  355. }
  356. return last;
  357. }
  358. const DEFAULT_MODIFIER = (str) => str;
  359. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  360. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  361. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : shared.join(values);
  362. const DEFAULT_INTERPOLATE = shared.toDisplayString;
  363. function pluralDefault(choice, choicesLength) {
  364. choice = Math.abs(choice);
  365. if (choicesLength === 2) {
  366. // prettier-ignore
  367. return choice
  368. ? choice > 1
  369. ? 1
  370. : 0
  371. : 1;
  372. }
  373. return choice ? Math.min(choice, 2) : 0;
  374. }
  375. function getPluralIndex(options) {
  376. // prettier-ignore
  377. const index = shared.isNumber(options.pluralIndex)
  378. ? options.pluralIndex
  379. : -1;
  380. // prettier-ignore
  381. return options.named && (shared.isNumber(options.named.count) || shared.isNumber(options.named.n))
  382. ? shared.isNumber(options.named.count)
  383. ? options.named.count
  384. : shared.isNumber(options.named.n)
  385. ? options.named.n
  386. : index
  387. : index;
  388. }
  389. function normalizeNamed(pluralIndex, props) {
  390. if (!props.count) {
  391. props.count = pluralIndex;
  392. }
  393. if (!props.n) {
  394. props.n = pluralIndex;
  395. }
  396. }
  397. function createMessageContext(options = {}) {
  398. const locale = options.locale;
  399. const pluralIndex = getPluralIndex(options);
  400. const pluralRule = shared.isObject(options.pluralRules) &&
  401. shared.isString(locale) &&
  402. shared.isFunction(options.pluralRules[locale])
  403. ? options.pluralRules[locale]
  404. : pluralDefault;
  405. const orgPluralRule = shared.isObject(options.pluralRules) &&
  406. shared.isString(locale) &&
  407. shared.isFunction(options.pluralRules[locale])
  408. ? pluralDefault
  409. : undefined;
  410. const plural = (messages) => {
  411. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  412. };
  413. const _list = options.list || [];
  414. const list = (index) => _list[index];
  415. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  416. const _named = options.named || shared.create();
  417. shared.isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  418. const named = (key) => _named[key];
  419. function message(key) {
  420. // prettier-ignore
  421. const msg = shared.isFunction(options.messages)
  422. ? options.messages(key)
  423. : shared.isObject(options.messages)
  424. ? options.messages[key]
  425. : false;
  426. return !msg
  427. ? options.parent
  428. ? options.parent.message(key) // resolve from parent messages
  429. : DEFAULT_MESSAGE
  430. : msg;
  431. }
  432. const _modifier = (name) => options.modifiers
  433. ? options.modifiers[name]
  434. : DEFAULT_MODIFIER;
  435. const normalize = shared.isPlainObject(options.processor) && shared.isFunction(options.processor.normalize)
  436. ? options.processor.normalize
  437. : DEFAULT_NORMALIZE;
  438. const interpolate = shared.isPlainObject(options.processor) &&
  439. shared.isFunction(options.processor.interpolate)
  440. ? options.processor.interpolate
  441. : DEFAULT_INTERPOLATE;
  442. const type = shared.isPlainObject(options.processor) && shared.isString(options.processor.type)
  443. ? options.processor.type
  444. : DEFAULT_MESSAGE_DATA_TYPE;
  445. const linked = (key, ...args) => {
  446. const [arg1, arg2] = args;
  447. let type = 'text';
  448. let modifier = '';
  449. if (args.length === 1) {
  450. if (shared.isObject(arg1)) {
  451. modifier = arg1.modifier || modifier;
  452. type = arg1.type || type;
  453. }
  454. else if (shared.isString(arg1)) {
  455. modifier = arg1 || modifier;
  456. }
  457. }
  458. else if (args.length === 2) {
  459. if (shared.isString(arg1)) {
  460. modifier = arg1 || modifier;
  461. }
  462. if (shared.isString(arg2)) {
  463. type = arg2 || type;
  464. }
  465. }
  466. const ret = message(key)(ctx);
  467. const msg =
  468. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  469. type === 'vnode' && shared.isArray(ret) && modifier
  470. ? ret[0]
  471. : ret;
  472. return modifier ? _modifier(modifier)(msg, type) : msg;
  473. };
  474. const ctx = {
  475. ["list" /* HelperNameMap.LIST */]: list,
  476. ["named" /* HelperNameMap.NAMED */]: named,
  477. ["plural" /* HelperNameMap.PLURAL */]: plural,
  478. ["linked" /* HelperNameMap.LINKED */]: linked,
  479. ["message" /* HelperNameMap.MESSAGE */]: message,
  480. ["type" /* HelperNameMap.TYPE */]: type,
  481. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  482. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  483. ["values" /* HelperNameMap.VALUES */]: shared.assign(shared.create(), _list, _named)
  484. };
  485. return ctx;
  486. }
  487. let devtools = null;
  488. function setDevToolsHook(hook) {
  489. devtools = hook;
  490. }
  491. function getDevToolsHook() {
  492. return devtools;
  493. }
  494. function initI18nDevTools(i18n, version, meta) {
  495. // TODO: queue if devtools is undefined
  496. devtools &&
  497. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  498. timestamp: Date.now(),
  499. i18n,
  500. version,
  501. meta
  502. });
  503. }
  504. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  505. function createDevToolsHook(hook) {
  506. return (payloads) => devtools && devtools.emit(hook, payloads);
  507. }
  508. const code$1 = messageCompiler.CompileWarnCodes.__EXTEND_POINT__;
  509. const inc$1 = shared.incrementer(code$1);
  510. const CoreWarnCodes = {
  511. NOT_FOUND_KEY: code$1, // 2
  512. FALLBACK_TO_TRANSLATE: inc$1(), // 3
  513. CANNOT_FORMAT_NUMBER: inc$1(), // 4
  514. FALLBACK_TO_NUMBER_FORMAT: inc$1(), // 5
  515. CANNOT_FORMAT_DATE: inc$1(), // 6
  516. FALLBACK_TO_DATE_FORMAT: inc$1(), // 7
  517. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(), // 8
  518. __EXTEND_POINT__: inc$1() // 9
  519. };
  520. /** @internal */
  521. const warnMessages = {
  522. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  523. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  524. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  525. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  526. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  527. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  528. [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.`
  529. };
  530. function getWarnMessage(code, ...args) {
  531. return shared.format(warnMessages[code], ...args);
  532. }
  533. const code = messageCompiler.CompileErrorCodes.__EXTEND_POINT__;
  534. const inc = shared.incrementer(code);
  535. const CoreErrorCodes = {
  536. INVALID_ARGUMENT: code, // 17
  537. INVALID_DATE_ARGUMENT: inc(), // 18
  538. INVALID_ISO_DATE_ARGUMENT: inc(), // 19
  539. NOT_SUPPORT_NON_STRING_MESSAGE: inc(), // 20
  540. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(), // 21
  541. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(), // 22
  542. NOT_SUPPORT_LOCALE_TYPE: inc(), // 23
  543. __EXTEND_POINT__: inc() // 24
  544. };
  545. function createCoreError(code) {
  546. return messageCompiler.createCompileError(code, null, { messages: errorMessages } );
  547. }
  548. /** @internal */
  549. const errorMessages = {
  550. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  551. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  552. 'Make sure your Date represents a valid date.',
  553. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  554. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  555. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  556. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  557. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  558. };
  559. /** @internal */
  560. function getLocale(context, options) {
  561. return options.locale != null
  562. ? resolveLocale(options.locale)
  563. : resolveLocale(context.locale);
  564. }
  565. let _resolveLocale;
  566. /** @internal */
  567. function resolveLocale(locale) {
  568. if (shared.isString(locale)) {
  569. return locale;
  570. }
  571. else {
  572. if (shared.isFunction(locale)) {
  573. if (locale.resolvedOnce && _resolveLocale != null) {
  574. return _resolveLocale;
  575. }
  576. else if (locale.constructor.name === 'Function') {
  577. const resolve = locale();
  578. if (shared.isPromise(resolve)) {
  579. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  580. }
  581. return (_resolveLocale = resolve);
  582. }
  583. else {
  584. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  585. }
  586. }
  587. else {
  588. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  589. }
  590. }
  591. }
  592. /**
  593. * Fallback with simple implemenation
  594. *
  595. * @remarks
  596. * A fallback locale function implemented with a simple fallback algorithm.
  597. *
  598. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  599. *
  600. * @param ctx - A {@link CoreContext | context}
  601. * @param fallback - A {@link FallbackLocale | fallback locale}
  602. * @param start - A starting {@link Locale | locale}
  603. *
  604. * @returns Fallback locales
  605. *
  606. * @VueI18nGeneral
  607. */
  608. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  609. ) {
  610. // prettier-ignore
  611. return [...new Set([
  612. start,
  613. ...(shared.isArray(fallback)
  614. ? fallback
  615. : shared.isObject(fallback)
  616. ? Object.keys(fallback)
  617. : shared.isString(fallback)
  618. ? [fallback]
  619. : [start])
  620. ])];
  621. }
  622. /**
  623. * Fallback with locale chain
  624. *
  625. * @remarks
  626. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  627. *
  628. * @param ctx - A {@link CoreContext | context}
  629. * @param fallback - A {@link FallbackLocale | fallback locale}
  630. * @param start - A starting {@link Locale | locale}
  631. *
  632. * @returns Fallback locales
  633. *
  634. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  635. *
  636. * @VueI18nGeneral
  637. */
  638. function fallbackWithLocaleChain(ctx, fallback, start) {
  639. const startLocale = shared.isString(start) ? start : DEFAULT_LOCALE;
  640. const context = ctx;
  641. if (!context.__localeChainCache) {
  642. context.__localeChainCache = new Map();
  643. }
  644. let chain = context.__localeChainCache.get(startLocale);
  645. if (!chain) {
  646. chain = [];
  647. // first block defined by start
  648. let block = [start];
  649. // while any intervening block found
  650. while (shared.isArray(block)) {
  651. block = appendBlockToChain(chain, block, fallback);
  652. }
  653. // prettier-ignore
  654. // last block defined by default
  655. const defaults = shared.isArray(fallback) || !shared.isPlainObject(fallback)
  656. ? fallback
  657. : fallback['default']
  658. ? fallback['default']
  659. : null;
  660. // convert defaults to array
  661. block = shared.isString(defaults) ? [defaults] : defaults;
  662. if (shared.isArray(block)) {
  663. appendBlockToChain(chain, block, false);
  664. }
  665. context.__localeChainCache.set(startLocale, chain);
  666. }
  667. return chain;
  668. }
  669. function appendBlockToChain(chain, block, blocks) {
  670. let follow = true;
  671. for (let i = 0; i < block.length && shared.isBoolean(follow); i++) {
  672. const locale = block[i];
  673. if (shared.isString(locale)) {
  674. follow = appendLocaleToChain(chain, block[i], blocks);
  675. }
  676. }
  677. return follow;
  678. }
  679. function appendLocaleToChain(chain, locale, blocks) {
  680. let follow;
  681. const tokens = locale.split('-');
  682. do {
  683. const target = tokens.join('-');
  684. follow = appendItemToChain(chain, target, blocks);
  685. tokens.splice(-1, 1);
  686. } while (tokens.length && follow === true);
  687. return follow;
  688. }
  689. function appendItemToChain(chain, target, blocks) {
  690. let follow = false;
  691. if (!chain.includes(target)) {
  692. follow = true;
  693. if (target) {
  694. follow = target[target.length - 1] !== '!';
  695. const locale = target.replace(/!/g, '');
  696. chain.push(locale);
  697. if ((shared.isArray(blocks) || shared.isPlainObject(blocks)) &&
  698. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  699. ) {
  700. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  701. follow = blocks[locale];
  702. }
  703. }
  704. }
  705. return follow;
  706. }
  707. /* eslint-disable @typescript-eslint/no-explicit-any */
  708. /**
  709. * Intlify core-base version
  710. * @internal
  711. */
  712. const VERSION = '9.14.5';
  713. const NOT_REOSLVED = -1;
  714. const DEFAULT_LOCALE = 'en-US';
  715. const MISSING_RESOLVE_VALUE = '';
  716. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  717. function getDefaultLinkedModifiers() {
  718. return {
  719. upper: (val, type) => {
  720. // prettier-ignore
  721. return type === 'text' && shared.isString(val)
  722. ? val.toUpperCase()
  723. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  724. ? val.children.toUpperCase()
  725. : val;
  726. },
  727. lower: (val, type) => {
  728. // prettier-ignore
  729. return type === 'text' && shared.isString(val)
  730. ? val.toLowerCase()
  731. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  732. ? val.children.toLowerCase()
  733. : val;
  734. },
  735. capitalize: (val, type) => {
  736. // prettier-ignore
  737. return (type === 'text' && shared.isString(val)
  738. ? capitalize(val)
  739. : type === 'vnode' && shared.isObject(val) && '__v_isVNode' in val
  740. ? capitalize(val.children)
  741. : val);
  742. }
  743. };
  744. }
  745. let _compiler;
  746. function registerMessageCompiler(compiler) {
  747. _compiler = compiler;
  748. }
  749. let _resolver;
  750. /**
  751. * Register the message resolver
  752. *
  753. * @param resolver - A {@link MessageResolver} function
  754. *
  755. * @VueI18nGeneral
  756. */
  757. function registerMessageResolver(resolver) {
  758. _resolver = resolver;
  759. }
  760. let _fallbacker;
  761. /**
  762. * Register the locale fallbacker
  763. *
  764. * @param fallbacker - A {@link LocaleFallbacker} function
  765. *
  766. * @VueI18nGeneral
  767. */
  768. function registerLocaleFallbacker(fallbacker) {
  769. _fallbacker = fallbacker;
  770. }
  771. // Additional Meta for Intlify DevTools
  772. let _additionalMeta = null;
  773. /* #__NO_SIDE_EFFECTS__ */
  774. const setAdditionalMeta = (meta) => {
  775. _additionalMeta = meta;
  776. };
  777. /* #__NO_SIDE_EFFECTS__ */
  778. const getAdditionalMeta = () => _additionalMeta;
  779. let _fallbackContext = null;
  780. const setFallbackContext = (context) => {
  781. _fallbackContext = context;
  782. };
  783. const getFallbackContext = () => _fallbackContext;
  784. // ID for CoreContext
  785. let _cid = 0;
  786. function createCoreContext(options = {}) {
  787. // setup options
  788. const onWarn = shared.isFunction(options.onWarn) ? options.onWarn : shared.warn;
  789. const version = shared.isString(options.version) ? options.version : VERSION;
  790. const locale = shared.isString(options.locale) || shared.isFunction(options.locale)
  791. ? options.locale
  792. : DEFAULT_LOCALE;
  793. const _locale = shared.isFunction(locale) ? DEFAULT_LOCALE : locale;
  794. const fallbackLocale = shared.isArray(options.fallbackLocale) ||
  795. shared.isPlainObject(options.fallbackLocale) ||
  796. shared.isString(options.fallbackLocale) ||
  797. options.fallbackLocale === false
  798. ? options.fallbackLocale
  799. : _locale;
  800. const messages = shared.isPlainObject(options.messages)
  801. ? options.messages
  802. : createResources(_locale);
  803. const datetimeFormats = shared.isPlainObject(options.datetimeFormats)
  804. ? options.datetimeFormats
  805. : createResources(_locale)
  806. ;
  807. const numberFormats = shared.isPlainObject(options.numberFormats)
  808. ? options.numberFormats
  809. : createResources(_locale)
  810. ;
  811. const modifiers = shared.assign(shared.create(), options.modifiers, getDefaultLinkedModifiers());
  812. const pluralRules = options.pluralRules || shared.create();
  813. const missing = shared.isFunction(options.missing) ? options.missing : null;
  814. const missingWarn = shared.isBoolean(options.missingWarn) || shared.isRegExp(options.missingWarn)
  815. ? options.missingWarn
  816. : true;
  817. const fallbackWarn = shared.isBoolean(options.fallbackWarn) || shared.isRegExp(options.fallbackWarn)
  818. ? options.fallbackWarn
  819. : true;
  820. const fallbackFormat = !!options.fallbackFormat;
  821. const unresolving = !!options.unresolving;
  822. const postTranslation = shared.isFunction(options.postTranslation)
  823. ? options.postTranslation
  824. : null;
  825. const processor = shared.isPlainObject(options.processor) ? options.processor : null;
  826. const warnHtmlMessage = shared.isBoolean(options.warnHtmlMessage)
  827. ? options.warnHtmlMessage
  828. : true;
  829. const escapeParameter = !!options.escapeParameter;
  830. const messageCompiler = shared.isFunction(options.messageCompiler)
  831. ? options.messageCompiler
  832. : _compiler;
  833. if (shared.isFunction(options.messageCompiler)) {
  834. shared.warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
  835. }
  836. const messageResolver = shared.isFunction(options.messageResolver)
  837. ? options.messageResolver
  838. : _resolver || resolveWithKeyValue;
  839. const localeFallbacker = shared.isFunction(options.localeFallbacker)
  840. ? options.localeFallbacker
  841. : _fallbacker || fallbackWithSimple;
  842. const fallbackContext = shared.isObject(options.fallbackContext)
  843. ? options.fallbackContext
  844. : undefined;
  845. // setup internal options
  846. const internalOptions = options;
  847. const __datetimeFormatters = shared.isObject(internalOptions.__datetimeFormatters)
  848. ? internalOptions.__datetimeFormatters
  849. : new Map()
  850. ;
  851. const __numberFormatters = shared.isObject(internalOptions.__numberFormatters)
  852. ? internalOptions.__numberFormatters
  853. : new Map()
  854. ;
  855. const __meta = shared.isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  856. _cid++;
  857. const context = {
  858. version,
  859. cid: _cid,
  860. locale,
  861. fallbackLocale,
  862. messages,
  863. modifiers,
  864. pluralRules,
  865. missing,
  866. missingWarn,
  867. fallbackWarn,
  868. fallbackFormat,
  869. unresolving,
  870. postTranslation,
  871. processor,
  872. warnHtmlMessage,
  873. escapeParameter,
  874. messageCompiler,
  875. messageResolver,
  876. localeFallbacker,
  877. fallbackContext,
  878. onWarn,
  879. __meta
  880. };
  881. {
  882. context.datetimeFormats = datetimeFormats;
  883. context.numberFormats = numberFormats;
  884. context.__datetimeFormatters = __datetimeFormatters;
  885. context.__numberFormatters = __numberFormatters;
  886. }
  887. // for vue-devtools timeline event
  888. {
  889. context.__v_emitter =
  890. internalOptions.__v_emitter != null
  891. ? internalOptions.__v_emitter
  892. : undefined;
  893. }
  894. // NOTE: experimental !!
  895. {
  896. initI18nDevTools(context, version, __meta);
  897. }
  898. return context;
  899. }
  900. const createResources = (locale) => ({ [locale]: shared.create() });
  901. /** @internal */
  902. function isTranslateFallbackWarn(fallback, key) {
  903. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  904. }
  905. /** @internal */
  906. function isTranslateMissingWarn(missing, key) {
  907. return missing instanceof RegExp ? missing.test(key) : missing;
  908. }
  909. /** @internal */
  910. function handleMissing(context, key, locale, missingWarn, type) {
  911. const { missing, onWarn } = context;
  912. // for vue-devtools timeline event
  913. {
  914. const emitter = context.__v_emitter;
  915. if (emitter) {
  916. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  917. locale,
  918. key,
  919. type,
  920. groupId: `${type}:${key}`
  921. });
  922. }
  923. }
  924. if (missing !== null) {
  925. const ret = missing(context, locale, key, type);
  926. return shared.isString(ret) ? ret : key;
  927. }
  928. else {
  929. if (isTranslateMissingWarn(missingWarn, key)) {
  930. onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  931. }
  932. return key;
  933. }
  934. }
  935. /** @internal */
  936. function updateFallbackLocale(ctx, locale, fallback) {
  937. const context = ctx;
  938. context.__localeChainCache = new Map();
  939. ctx.localeFallbacker(ctx, fallback, locale);
  940. }
  941. /** @internal */
  942. function isAlmostSameLocale(locale, compareLocale) {
  943. if (locale === compareLocale)
  944. return false;
  945. return locale.split('-')[0] === compareLocale.split('-')[0];
  946. }
  947. /** @internal */
  948. function isImplicitFallback(targetLocale, locales) {
  949. const index = locales.indexOf(targetLocale);
  950. if (index === -1) {
  951. return false;
  952. }
  953. for (let i = index + 1; i < locales.length; i++) {
  954. if (isAlmostSameLocale(targetLocale, locales[i])) {
  955. return true;
  956. }
  957. }
  958. return false;
  959. }
  960. /* eslint-enable @typescript-eslint/no-explicit-any */
  961. function format(ast) {
  962. const msg = (ctx) => formatParts(ctx, ast);
  963. return msg;
  964. }
  965. function formatParts(ctx, ast) {
  966. const body = resolveBody(ast);
  967. if (body == null) {
  968. throw createUnhandleNodeError(0 /* NodeTypes.Resource */);
  969. }
  970. const type = resolveType(body);
  971. if (type === 1 /* NodeTypes.Plural */) {
  972. const plural = body;
  973. const cases = resolveCases(plural);
  974. return ctx.plural(cases.reduce((messages, c) => [
  975. ...messages,
  976. formatMessageParts(ctx, c)
  977. ], []));
  978. }
  979. else {
  980. return formatMessageParts(ctx, body);
  981. }
  982. }
  983. function formatMessageParts(ctx, node) {
  984. const static_ = resolveStatic(node);
  985. if (static_ != null) {
  986. return ctx.type === 'text'
  987. ? static_
  988. : ctx.normalize([static_]);
  989. }
  990. else {
  991. const messages = resolveItems(node).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  992. return ctx.normalize(messages);
  993. }
  994. }
  995. function formatMessagePart(ctx, node) {
  996. const type = resolveType(node);
  997. switch (type) {
  998. case 3 /* NodeTypes.Text */: {
  999. return resolveValue$1(node, type);
  1000. }
  1001. case 9 /* NodeTypes.Literal */: {
  1002. return resolveValue$1(node, type);
  1003. }
  1004. case 4 /* NodeTypes.Named */: {
  1005. const named = node;
  1006. if (shared.hasOwn(named, 'k') && named.k) {
  1007. return ctx.interpolate(ctx.named(named.k));
  1008. }
  1009. if (shared.hasOwn(named, 'key') && named.key) {
  1010. return ctx.interpolate(ctx.named(named.key));
  1011. }
  1012. throw createUnhandleNodeError(type);
  1013. }
  1014. case 5 /* NodeTypes.List */: {
  1015. const list = node;
  1016. if (shared.hasOwn(list, 'i') && shared.isNumber(list.i)) {
  1017. return ctx.interpolate(ctx.list(list.i));
  1018. }
  1019. if (shared.hasOwn(list, 'index') && shared.isNumber(list.index)) {
  1020. return ctx.interpolate(ctx.list(list.index));
  1021. }
  1022. throw createUnhandleNodeError(type);
  1023. }
  1024. case 6 /* NodeTypes.Linked */: {
  1025. const linked = node;
  1026. const modifier = resolveLinkedModifier(linked);
  1027. const key = resolveLinkedKey(linked);
  1028. return ctx.linked(formatMessagePart(ctx, key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  1029. }
  1030. case 7 /* NodeTypes.LinkedKey */: {
  1031. return resolveValue$1(node, type);
  1032. }
  1033. case 8 /* NodeTypes.LinkedModifier */: {
  1034. return resolveValue$1(node, type);
  1035. }
  1036. default:
  1037. throw new Error(`unhandled node on format message part: ${type}`);
  1038. }
  1039. }
  1040. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  1041. function checkHtmlMessage(source, warnHtmlMessage) {
  1042. if (warnHtmlMessage && messageCompiler.detectHtmlTag(source)) {
  1043. shared.warn(shared.format(WARN_MESSAGE, { source }));
  1044. }
  1045. }
  1046. const defaultOnCacheKey = (message) => message;
  1047. let compileCache = shared.create();
  1048. function onCompileWarn(_warn) {
  1049. if (_warn.code === messageCompiler.CompileWarnCodes.USE_MODULO_SYNTAX) {
  1050. shared.warn(`The use of named interpolation with modulo syntax is deprecated. ` +
  1051. `It will be removed in v10.\n` +
  1052. `reference: https://vue-i18n.intlify.dev/guide/essentials/syntax#rails-i18n-format \n` +
  1053. `(message compiler warning message: ${_warn.message})`);
  1054. }
  1055. }
  1056. function clearCompileCache() {
  1057. compileCache = shared.create();
  1058. }
  1059. function baseCompile(message, options = {}) {
  1060. // error detecting on compile
  1061. let detectError = false;
  1062. const onError = options.onError || messageCompiler.defaultOnError;
  1063. options.onError = (err) => {
  1064. detectError = true;
  1065. onError(err);
  1066. };
  1067. // compile with mesasge-compiler
  1068. return { ...messageCompiler.baseCompile(message, options), detectError };
  1069. }
  1070. /* #__NO_SIDE_EFFECTS__ */
  1071. const compileToFunction = (message, context) => {
  1072. if (!shared.isString(message)) {
  1073. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);
  1074. }
  1075. // set onWarn
  1076. {
  1077. context.onWarn = onCompileWarn;
  1078. }
  1079. {
  1080. // check HTML message
  1081. const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
  1082. ? context.warnHtmlMessage
  1083. : true;
  1084. checkHtmlMessage(message, warnHtmlMessage);
  1085. // check caches
  1086. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  1087. const cacheKey = onCacheKey(message);
  1088. const cached = compileCache[cacheKey];
  1089. if (cached) {
  1090. return cached;
  1091. }
  1092. // compile
  1093. const { code, detectError } = baseCompile(message, context);
  1094. // evaluate function
  1095. const msg = new Function(`return ${code}`)();
  1096. // if occurred compile error, don't cache
  1097. return !detectError
  1098. ? (compileCache[cacheKey] = msg)
  1099. : msg;
  1100. }
  1101. };
  1102. function compile(message, context) {
  1103. // set onWarn
  1104. {
  1105. context.onWarn = onCompileWarn;
  1106. }
  1107. if (shared.isString(message)) {
  1108. // check HTML message
  1109. const warnHtmlMessage = shared.isBoolean(context.warnHtmlMessage)
  1110. ? context.warnHtmlMessage
  1111. : true;
  1112. checkHtmlMessage(message, warnHtmlMessage);
  1113. // check caches
  1114. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  1115. const cacheKey = onCacheKey(message);
  1116. const cached = compileCache[cacheKey];
  1117. if (cached) {
  1118. return cached;
  1119. }
  1120. // compile with JIT mode
  1121. const { ast, detectError } = baseCompile(message, {
  1122. ...context,
  1123. location: true,
  1124. jit: true
  1125. });
  1126. // compose message function from AST
  1127. const msg = format(ast);
  1128. // if occurred compile error, don't cache
  1129. return !detectError
  1130. ? (compileCache[cacheKey] = msg)
  1131. : msg;
  1132. }
  1133. else {
  1134. if (!isMessageAST(message)) {
  1135. shared.warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  1136. return (() => message);
  1137. }
  1138. // AST case (passed from bundler)
  1139. const cacheKey = message.cacheKey;
  1140. if (cacheKey) {
  1141. const cached = compileCache[cacheKey];
  1142. if (cached) {
  1143. return cached;
  1144. }
  1145. // compose message function from message (AST)
  1146. return (compileCache[cacheKey] =
  1147. format(message));
  1148. }
  1149. else {
  1150. return format(message);
  1151. }
  1152. }
  1153. }
  1154. const NOOP_MESSAGE_FUNCTION = () => '';
  1155. const isMessageFunction = (val) => shared.isFunction(val);
  1156. // implementation of `translate` function
  1157. function translate(context, ...args) {
  1158. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  1159. const [key, options] = parseTranslateArgs(...args);
  1160. const missingWarn = shared.isBoolean(options.missingWarn)
  1161. ? options.missingWarn
  1162. : context.missingWarn;
  1163. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1164. ? options.fallbackWarn
  1165. : context.fallbackWarn;
  1166. const escapeParameter = shared.isBoolean(options.escapeParameter)
  1167. ? options.escapeParameter
  1168. : context.escapeParameter;
  1169. const resolvedMessage = !!options.resolvedMessage;
  1170. // prettier-ignore
  1171. const defaultMsgOrKey = shared.isString(options.default) || shared.isBoolean(options.default) // default by function option
  1172. ? !shared.isBoolean(options.default)
  1173. ? options.default
  1174. : (!messageCompiler ? () => key : key)
  1175. : fallbackFormat // default by `fallbackFormat` option
  1176. ? (!messageCompiler ? () => key : key)
  1177. : '';
  1178. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  1179. const locale = getLocale(context, options);
  1180. // escape params
  1181. escapeParameter && escapeParams(options);
  1182. // resolve message format
  1183. // eslint-disable-next-line prefer-const
  1184. let [formatScope, targetLocale, message] = !resolvedMessage
  1185. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  1186. : [
  1187. key,
  1188. locale,
  1189. messages[locale] || shared.create()
  1190. ];
  1191. // NOTE:
  1192. // Fix to work around `ssrTransfrom` bug in Vite.
  1193. // https://github.com/vitejs/vite/issues/4306
  1194. // To get around this, use temporary variables.
  1195. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  1196. let format = formatScope;
  1197. // if you use default message, set it as message format!
  1198. let cacheBaseKey = key;
  1199. if (!resolvedMessage &&
  1200. !(shared.isString(format) ||
  1201. isMessageAST(format) ||
  1202. isMessageFunction(format))) {
  1203. if (enableDefaultMsg) {
  1204. format = defaultMsgOrKey;
  1205. cacheBaseKey = format;
  1206. }
  1207. }
  1208. // checking message format and target locale
  1209. if (!resolvedMessage &&
  1210. (!(shared.isString(format) ||
  1211. isMessageAST(format) ||
  1212. isMessageFunction(format)) ||
  1213. !shared.isString(targetLocale))) {
  1214. return unresolving ? NOT_REOSLVED : key;
  1215. }
  1216. // TODO: refactor
  1217. if (shared.isString(format) && context.messageCompiler == null) {
  1218. shared.warn(`The message format compilation is not supported in this build. ` +
  1219. `Because message compiler isn't included. ` +
  1220. `You need to pre-compilation all message format. ` +
  1221. `So translate function return '${key}'.`);
  1222. return key;
  1223. }
  1224. // setup compile error detecting
  1225. let occurred = false;
  1226. const onError = () => {
  1227. occurred = true;
  1228. };
  1229. // compile message format
  1230. const msg = !isMessageFunction(format)
  1231. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  1232. : format;
  1233. // if occurred compile error, return the message format
  1234. if (occurred) {
  1235. return format;
  1236. }
  1237. // evaluate message with context
  1238. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  1239. const msgContext = createMessageContext(ctxOptions);
  1240. const messaged = evaluateMessage(context, msg, msgContext);
  1241. // if use post translation option, proceed it with handler
  1242. let ret = postTranslation
  1243. ? postTranslation(messaged, key)
  1244. : messaged;
  1245. // apply HTML sanitization for security
  1246. if (escapeParameter && shared.isString(ret)) {
  1247. ret = shared.sanitizeTranslatedHtml(ret);
  1248. }
  1249. // NOTE: experimental !!
  1250. {
  1251. // prettier-ignore
  1252. const payloads = {
  1253. timestamp: Date.now(),
  1254. key: shared.isString(key)
  1255. ? key
  1256. : isMessageFunction(format)
  1257. ? format.key
  1258. : '',
  1259. locale: targetLocale || (isMessageFunction(format)
  1260. ? format.locale
  1261. : ''),
  1262. format: shared.isString(format)
  1263. ? format
  1264. : isMessageFunction(format)
  1265. ? format.source
  1266. : '',
  1267. message: ret
  1268. };
  1269. payloads.meta = shared.assign({}, context.__meta, getAdditionalMeta() || {});
  1270. translateDevTools(payloads);
  1271. }
  1272. return ret;
  1273. }
  1274. function escapeParams(options) {
  1275. if (shared.isArray(options.list)) {
  1276. options.list = options.list.map(item => shared.isString(item) ? shared.escapeHtml(item) : item);
  1277. }
  1278. else if (shared.isObject(options.named)) {
  1279. Object.keys(options.named).forEach(key => {
  1280. if (shared.isString(options.named[key])) {
  1281. options.named[key] = shared.escapeHtml(options.named[key]);
  1282. }
  1283. });
  1284. }
  1285. }
  1286. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  1287. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  1288. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  1289. let message = shared.create();
  1290. let targetLocale;
  1291. let format = null;
  1292. let from = locale;
  1293. let to = null;
  1294. const type = 'translate';
  1295. for (let i = 0; i < locales.length; i++) {
  1296. targetLocale = to = locales[i];
  1297. if (locale !== targetLocale &&
  1298. !isAlmostSameLocale(locale, targetLocale) &&
  1299. isTranslateFallbackWarn(fallbackWarn, key)) {
  1300. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  1301. key,
  1302. target: targetLocale
  1303. }));
  1304. }
  1305. // for vue-devtools timeline event
  1306. if (locale !== targetLocale) {
  1307. const emitter = context.__v_emitter;
  1308. if (emitter) {
  1309. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1310. type,
  1311. key,
  1312. from,
  1313. to,
  1314. groupId: `${type}:${key}`
  1315. });
  1316. }
  1317. }
  1318. message =
  1319. messages[targetLocale] || shared.create();
  1320. // for vue-devtools timeline event
  1321. let start = null;
  1322. let startTag;
  1323. let endTag;
  1324. if (shared.inBrowser) {
  1325. start = window.performance.now();
  1326. startTag = 'intlify-message-resolve-start';
  1327. endTag = 'intlify-message-resolve-end';
  1328. shared.mark && shared.mark(startTag);
  1329. }
  1330. if ((format = resolveValue(message, key)) === null) {
  1331. // if null, resolve with object key path
  1332. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1333. }
  1334. // for vue-devtools timeline event
  1335. if (shared.inBrowser) {
  1336. const end = window.performance.now();
  1337. const emitter = context.__v_emitter;
  1338. if (emitter && start && format) {
  1339. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  1340. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  1341. key,
  1342. message: format,
  1343. time: end - start,
  1344. groupId: `${type}:${key}`
  1345. });
  1346. }
  1347. if (startTag && endTag && shared.mark && shared.measure) {
  1348. shared.mark(endTag);
  1349. shared.measure('intlify message resolve', startTag, endTag);
  1350. }
  1351. }
  1352. if (shared.isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  1353. break;
  1354. }
  1355. if (!isImplicitFallback(targetLocale, locales)) {
  1356. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1357. key, targetLocale, missingWarn, type);
  1358. if (missingRet !== key) {
  1359. format = missingRet;
  1360. }
  1361. }
  1362. from = to;
  1363. }
  1364. return [format, targetLocale, message];
  1365. }
  1366. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  1367. const { messageCompiler, warnHtmlMessage } = context;
  1368. if (isMessageFunction(format)) {
  1369. const msg = format;
  1370. msg.locale = msg.locale || targetLocale;
  1371. msg.key = msg.key || key;
  1372. return msg;
  1373. }
  1374. if (messageCompiler == null) {
  1375. const msg = (() => format);
  1376. msg.locale = targetLocale;
  1377. msg.key = key;
  1378. return msg;
  1379. }
  1380. // for vue-devtools timeline event
  1381. let start = null;
  1382. let startTag;
  1383. let endTag;
  1384. if (shared.inBrowser) {
  1385. start = window.performance.now();
  1386. startTag = 'intlify-message-compilation-start';
  1387. endTag = 'intlify-message-compilation-end';
  1388. shared.mark && shared.mark(startTag);
  1389. }
  1390. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  1391. // for vue-devtools timeline event
  1392. if (shared.inBrowser) {
  1393. const end = window.performance.now();
  1394. const emitter = context.__v_emitter;
  1395. if (emitter && start) {
  1396. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  1397. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  1398. message: format,
  1399. time: end - start,
  1400. groupId: `${'translate'}:${key}`
  1401. });
  1402. }
  1403. if (startTag && endTag && shared.mark && shared.measure) {
  1404. shared.mark(endTag);
  1405. shared.measure('intlify message compilation', startTag, endTag);
  1406. }
  1407. }
  1408. msg.locale = targetLocale;
  1409. msg.key = key;
  1410. msg.source = format;
  1411. return msg;
  1412. }
  1413. function evaluateMessage(context, msg, msgCtx) {
  1414. // for vue-devtools timeline event
  1415. let start = null;
  1416. let startTag;
  1417. let endTag;
  1418. if (shared.inBrowser) {
  1419. start = window.performance.now();
  1420. startTag = 'intlify-message-evaluation-start';
  1421. endTag = 'intlify-message-evaluation-end';
  1422. shared.mark && shared.mark(startTag);
  1423. }
  1424. const messaged = msg(msgCtx);
  1425. // for vue-devtools timeline event
  1426. if (shared.inBrowser) {
  1427. const end = window.performance.now();
  1428. const emitter = context.__v_emitter;
  1429. if (emitter && start) {
  1430. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  1431. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  1432. value: messaged,
  1433. time: end - start,
  1434. groupId: `${'translate'}:${msg.key}`
  1435. });
  1436. }
  1437. if (startTag && endTag && shared.mark && shared.measure) {
  1438. shared.mark(endTag);
  1439. shared.measure('intlify message evaluation', startTag, endTag);
  1440. }
  1441. }
  1442. return messaged;
  1443. }
  1444. /** @internal */
  1445. function parseTranslateArgs(...args) {
  1446. const [arg1, arg2, arg3] = args;
  1447. const options = shared.create();
  1448. if (!shared.isString(arg1) &&
  1449. !shared.isNumber(arg1) &&
  1450. !isMessageFunction(arg1) &&
  1451. !isMessageAST(arg1)) {
  1452. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1453. }
  1454. // prettier-ignore
  1455. const key = shared.isNumber(arg1)
  1456. ? String(arg1)
  1457. : isMessageFunction(arg1)
  1458. ? arg1
  1459. : arg1;
  1460. if (shared.isNumber(arg2)) {
  1461. options.plural = arg2;
  1462. }
  1463. else if (shared.isString(arg2)) {
  1464. options.default = arg2;
  1465. }
  1466. else if (shared.isPlainObject(arg2) && !shared.isEmptyObject(arg2)) {
  1467. options.named = arg2;
  1468. }
  1469. else if (shared.isArray(arg2)) {
  1470. options.list = arg2;
  1471. }
  1472. if (shared.isNumber(arg3)) {
  1473. options.plural = arg3;
  1474. }
  1475. else if (shared.isString(arg3)) {
  1476. options.default = arg3;
  1477. }
  1478. else if (shared.isPlainObject(arg3)) {
  1479. shared.assign(options, arg3);
  1480. }
  1481. return [key, options];
  1482. }
  1483. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  1484. return {
  1485. locale,
  1486. key,
  1487. warnHtmlMessage,
  1488. onError: (err) => {
  1489. onError && onError(err);
  1490. {
  1491. const _source = getSourceForCodeFrame(source);
  1492. const message = `Message compilation error: ${err.message}`;
  1493. const codeFrame = err.location &&
  1494. _source &&
  1495. shared.generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  1496. const emitter = context.__v_emitter;
  1497. if (emitter && _source) {
  1498. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  1499. message: _source,
  1500. error: err.message,
  1501. start: err.location && err.location.start.offset,
  1502. end: err.location && err.location.end.offset,
  1503. groupId: `${'translate'}:${key}`
  1504. });
  1505. }
  1506. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1507. }
  1508. },
  1509. onCacheKey: (source) => shared.generateFormatCacheKey(locale, key, source)
  1510. };
  1511. }
  1512. function getSourceForCodeFrame(source) {
  1513. if (shared.isString(source)) {
  1514. return source;
  1515. }
  1516. else {
  1517. if (source.loc && source.loc.source) {
  1518. return source.loc.source;
  1519. }
  1520. }
  1521. }
  1522. function getMessageContextOptions(context, locale, message, options) {
  1523. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  1524. const resolveMessage = (key) => {
  1525. let val = resolveValue(message, key);
  1526. // fallback to root context
  1527. if (val == null && fallbackContext) {
  1528. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  1529. val = resolveValue(message, key);
  1530. }
  1531. if (shared.isString(val) || isMessageAST(val)) {
  1532. let occurred = false;
  1533. const onError = () => {
  1534. occurred = true;
  1535. };
  1536. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  1537. return !occurred
  1538. ? msg
  1539. : NOOP_MESSAGE_FUNCTION;
  1540. }
  1541. else if (isMessageFunction(val)) {
  1542. return val;
  1543. }
  1544. else {
  1545. // TODO: should be implemented warning message
  1546. return NOOP_MESSAGE_FUNCTION;
  1547. }
  1548. };
  1549. const ctxOptions = {
  1550. locale,
  1551. modifiers,
  1552. pluralRules,
  1553. messages: resolveMessage
  1554. };
  1555. if (context.processor) {
  1556. ctxOptions.processor = context.processor;
  1557. }
  1558. if (options.list) {
  1559. ctxOptions.list = options.list;
  1560. }
  1561. if (options.named) {
  1562. ctxOptions.named = options.named;
  1563. }
  1564. if (shared.isNumber(options.plural)) {
  1565. ctxOptions.pluralIndex = options.plural;
  1566. }
  1567. return ctxOptions;
  1568. }
  1569. const intlDefined = typeof Intl !== 'undefined';
  1570. const Availabilities = {
  1571. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1572. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1573. };
  1574. // implementation of `datetime` function
  1575. function datetime(context, ...args) {
  1576. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1577. const { __datetimeFormatters } = context;
  1578. if (!Availabilities.dateTimeFormat) {
  1579. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
  1580. return MISSING_RESOLVE_VALUE;
  1581. }
  1582. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1583. const missingWarn = shared.isBoolean(options.missingWarn)
  1584. ? options.missingWarn
  1585. : context.missingWarn;
  1586. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1587. ? options.fallbackWarn
  1588. : context.fallbackWarn;
  1589. const part = !!options.part;
  1590. const locale = getLocale(context, options);
  1591. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1592. fallbackLocale, locale);
  1593. if (!shared.isString(key) || key === '') {
  1594. return new Intl.DateTimeFormat(locale, overrides).format(value);
  1595. }
  1596. // resolve format
  1597. let datetimeFormat = {};
  1598. let targetLocale;
  1599. let format = null;
  1600. let from = locale;
  1601. let to = null;
  1602. const type = 'datetime format';
  1603. for (let i = 0; i < locales.length; i++) {
  1604. targetLocale = to = locales[i];
  1605. if (locale !== targetLocale &&
  1606. isTranslateFallbackWarn(fallbackWarn, key)) {
  1607. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  1608. key,
  1609. target: targetLocale
  1610. }));
  1611. }
  1612. // for vue-devtools timeline event
  1613. if (locale !== targetLocale) {
  1614. const emitter = context.__v_emitter;
  1615. if (emitter) {
  1616. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1617. type,
  1618. key,
  1619. from,
  1620. to,
  1621. groupId: `${type}:${key}`
  1622. });
  1623. }
  1624. }
  1625. datetimeFormat =
  1626. datetimeFormats[targetLocale] || {};
  1627. format = datetimeFormat[key];
  1628. if (shared.isPlainObject(format))
  1629. break;
  1630. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1631. from = to;
  1632. }
  1633. // checking format and target locale
  1634. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1635. return unresolving ? NOT_REOSLVED : key;
  1636. }
  1637. let id = `${targetLocale}__${key}`;
  1638. if (!shared.isEmptyObject(overrides)) {
  1639. id = `${id}__${JSON.stringify(overrides)}`;
  1640. }
  1641. let formatter = __datetimeFormatters.get(id);
  1642. if (!formatter) {
  1643. formatter = new Intl.DateTimeFormat(targetLocale, shared.assign({}, format, overrides));
  1644. __datetimeFormatters.set(id, formatter);
  1645. }
  1646. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1647. }
  1648. /** @internal */
  1649. const DATETIME_FORMAT_OPTIONS_KEYS = [
  1650. 'localeMatcher',
  1651. 'weekday',
  1652. 'era',
  1653. 'year',
  1654. 'month',
  1655. 'day',
  1656. 'hour',
  1657. 'minute',
  1658. 'second',
  1659. 'timeZoneName',
  1660. 'formatMatcher',
  1661. 'hour12',
  1662. 'timeZone',
  1663. 'dateStyle',
  1664. 'timeStyle',
  1665. 'calendar',
  1666. 'dayPeriod',
  1667. 'numberingSystem',
  1668. 'hourCycle',
  1669. 'fractionalSecondDigits'
  1670. ];
  1671. /** @internal */
  1672. function parseDateTimeArgs(...args) {
  1673. const [arg1, arg2, arg3, arg4] = args;
  1674. const options = shared.create();
  1675. let overrides = shared.create();
  1676. let value;
  1677. if (shared.isString(arg1)) {
  1678. // Only allow ISO strings - other date formats are often supported,
  1679. // but may cause different results in different browsers.
  1680. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  1681. if (!matches) {
  1682. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1683. }
  1684. // Some browsers can not parse the iso datetime separated by space,
  1685. // this is a compromise solution by replace the 'T'/' ' with 'T'
  1686. const dateTime = matches[3]
  1687. ? matches[3].trim().startsWith('T')
  1688. ? `${matches[1].trim()}${matches[3].trim()}`
  1689. : `${matches[1].trim()}T${matches[3].trim()}`
  1690. : matches[1].trim();
  1691. value = new Date(dateTime);
  1692. try {
  1693. // This will fail if the date is not valid
  1694. value.toISOString();
  1695. }
  1696. catch (e) {
  1697. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1698. }
  1699. }
  1700. else if (shared.isDate(arg1)) {
  1701. if (isNaN(arg1.getTime())) {
  1702. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  1703. }
  1704. value = arg1;
  1705. }
  1706. else if (shared.isNumber(arg1)) {
  1707. value = arg1;
  1708. }
  1709. else {
  1710. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1711. }
  1712. if (shared.isString(arg2)) {
  1713. options.key = arg2;
  1714. }
  1715. else if (shared.isPlainObject(arg2)) {
  1716. Object.keys(arg2).forEach(key => {
  1717. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  1718. overrides[key] = arg2[key];
  1719. }
  1720. else {
  1721. options[key] = arg2[key];
  1722. }
  1723. });
  1724. }
  1725. if (shared.isString(arg3)) {
  1726. options.locale = arg3;
  1727. }
  1728. else if (shared.isPlainObject(arg3)) {
  1729. overrides = arg3;
  1730. }
  1731. if (shared.isPlainObject(arg4)) {
  1732. overrides = arg4;
  1733. }
  1734. return [options.key || '', value, options, overrides];
  1735. }
  1736. /** @internal */
  1737. function clearDateTimeFormat(ctx, locale, format) {
  1738. const context = ctx;
  1739. for (const key in format) {
  1740. const id = `${locale}__${key}`;
  1741. if (!context.__datetimeFormatters.has(id)) {
  1742. continue;
  1743. }
  1744. context.__datetimeFormatters.delete(id);
  1745. }
  1746. }
  1747. // implementation of `number` function
  1748. function number(context, ...args) {
  1749. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1750. const { __numberFormatters } = context;
  1751. if (!Availabilities.numberFormat) {
  1752. onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  1753. return MISSING_RESOLVE_VALUE;
  1754. }
  1755. const [key, value, options, overrides] = parseNumberArgs(...args);
  1756. const missingWarn = shared.isBoolean(options.missingWarn)
  1757. ? options.missingWarn
  1758. : context.missingWarn;
  1759. const fallbackWarn = shared.isBoolean(options.fallbackWarn)
  1760. ? options.fallbackWarn
  1761. : context.fallbackWarn;
  1762. const part = !!options.part;
  1763. const locale = getLocale(context, options);
  1764. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1765. fallbackLocale, locale);
  1766. if (!shared.isString(key) || key === '') {
  1767. return new Intl.NumberFormat(locale, overrides).format(value);
  1768. }
  1769. // resolve format
  1770. let numberFormat = {};
  1771. let targetLocale;
  1772. let format = null;
  1773. let from = locale;
  1774. let to = null;
  1775. const type = 'number format';
  1776. for (let i = 0; i < locales.length; i++) {
  1777. targetLocale = to = locales[i];
  1778. if (locale !== targetLocale &&
  1779. isTranslateFallbackWarn(fallbackWarn, key)) {
  1780. onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  1781. key,
  1782. target: targetLocale
  1783. }));
  1784. }
  1785. // for vue-devtools timeline event
  1786. if (locale !== targetLocale) {
  1787. const emitter = context.__v_emitter;
  1788. if (emitter) {
  1789. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1790. type,
  1791. key,
  1792. from,
  1793. to,
  1794. groupId: `${type}:${key}`
  1795. });
  1796. }
  1797. }
  1798. numberFormat =
  1799. numberFormats[targetLocale] || {};
  1800. format = numberFormat[key];
  1801. if (shared.isPlainObject(format))
  1802. break;
  1803. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1804. from = to;
  1805. }
  1806. // checking format and target locale
  1807. if (!shared.isPlainObject(format) || !shared.isString(targetLocale)) {
  1808. return unresolving ? NOT_REOSLVED : key;
  1809. }
  1810. let id = `${targetLocale}__${key}`;
  1811. if (!shared.isEmptyObject(overrides)) {
  1812. id = `${id}__${JSON.stringify(overrides)}`;
  1813. }
  1814. let formatter = __numberFormatters.get(id);
  1815. if (!formatter) {
  1816. formatter = new Intl.NumberFormat(targetLocale, shared.assign({}, format, overrides));
  1817. __numberFormatters.set(id, formatter);
  1818. }
  1819. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1820. }
  1821. /** @internal */
  1822. const NUMBER_FORMAT_OPTIONS_KEYS = [
  1823. 'localeMatcher',
  1824. 'style',
  1825. 'currency',
  1826. 'currencyDisplay',
  1827. 'currencySign',
  1828. 'useGrouping',
  1829. 'minimumIntegerDigits',
  1830. 'minimumFractionDigits',
  1831. 'maximumFractionDigits',
  1832. 'minimumSignificantDigits',
  1833. 'maximumSignificantDigits',
  1834. 'compactDisplay',
  1835. 'notation',
  1836. 'signDisplay',
  1837. 'unit',
  1838. 'unitDisplay',
  1839. 'roundingMode',
  1840. 'roundingPriority',
  1841. 'roundingIncrement',
  1842. 'trailingZeroDisplay'
  1843. ];
  1844. /** @internal */
  1845. function parseNumberArgs(...args) {
  1846. const [arg1, arg2, arg3, arg4] = args;
  1847. const options = shared.create();
  1848. let overrides = shared.create();
  1849. if (!shared.isNumber(arg1)) {
  1850. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1851. }
  1852. const value = arg1;
  1853. if (shared.isString(arg2)) {
  1854. options.key = arg2;
  1855. }
  1856. else if (shared.isPlainObject(arg2)) {
  1857. Object.keys(arg2).forEach(key => {
  1858. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  1859. overrides[key] = arg2[key];
  1860. }
  1861. else {
  1862. options[key] = arg2[key];
  1863. }
  1864. });
  1865. }
  1866. if (shared.isString(arg3)) {
  1867. options.locale = arg3;
  1868. }
  1869. else if (shared.isPlainObject(arg3)) {
  1870. overrides = arg3;
  1871. }
  1872. if (shared.isPlainObject(arg4)) {
  1873. overrides = arg4;
  1874. }
  1875. return [options.key || '', value, options, overrides];
  1876. }
  1877. /** @internal */
  1878. function clearNumberFormat(ctx, locale, format) {
  1879. const context = ctx;
  1880. for (const key in format) {
  1881. const id = `${locale}__${key}`;
  1882. if (!context.__numberFormatters.has(id)) {
  1883. continue;
  1884. }
  1885. context.__numberFormatters.delete(id);
  1886. }
  1887. }
  1888. exports.CompileErrorCodes = messageCompiler.CompileErrorCodes;
  1889. exports.createCompileError = messageCompiler.createCompileError;
  1890. exports.AST_NODE_PROPS_KEYS = AST_NODE_PROPS_KEYS;
  1891. exports.CoreErrorCodes = CoreErrorCodes;
  1892. exports.CoreWarnCodes = CoreWarnCodes;
  1893. exports.DATETIME_FORMAT_OPTIONS_KEYS = DATETIME_FORMAT_OPTIONS_KEYS;
  1894. exports.DEFAULT_LOCALE = DEFAULT_LOCALE;
  1895. exports.DEFAULT_MESSAGE_DATA_TYPE = DEFAULT_MESSAGE_DATA_TYPE;
  1896. exports.MISSING_RESOLVE_VALUE = MISSING_RESOLVE_VALUE;
  1897. exports.NOT_REOSLVED = NOT_REOSLVED;
  1898. exports.NUMBER_FORMAT_OPTIONS_KEYS = NUMBER_FORMAT_OPTIONS_KEYS;
  1899. exports.VERSION = VERSION;
  1900. exports.clearCompileCache = clearCompileCache;
  1901. exports.clearDateTimeFormat = clearDateTimeFormat;
  1902. exports.clearNumberFormat = clearNumberFormat;
  1903. exports.compile = compile;
  1904. exports.compileToFunction = compileToFunction;
  1905. exports.createCoreContext = createCoreContext;
  1906. exports.createCoreError = createCoreError;
  1907. exports.createMessageContext = createMessageContext;
  1908. exports.datetime = datetime;
  1909. exports.fallbackWithLocaleChain = fallbackWithLocaleChain;
  1910. exports.fallbackWithSimple = fallbackWithSimple;
  1911. exports.getAdditionalMeta = getAdditionalMeta;
  1912. exports.getDevToolsHook = getDevToolsHook;
  1913. exports.getFallbackContext = getFallbackContext;
  1914. exports.getLocale = getLocale;
  1915. exports.getWarnMessage = getWarnMessage;
  1916. exports.handleMissing = handleMissing;
  1917. exports.initI18nDevTools = initI18nDevTools;
  1918. exports.isAlmostSameLocale = isAlmostSameLocale;
  1919. exports.isImplicitFallback = isImplicitFallback;
  1920. exports.isMessageAST = isMessageAST;
  1921. exports.isMessageFunction = isMessageFunction;
  1922. exports.isTranslateFallbackWarn = isTranslateFallbackWarn;
  1923. exports.isTranslateMissingWarn = isTranslateMissingWarn;
  1924. exports.number = number;
  1925. exports.parse = parse;
  1926. exports.parseDateTimeArgs = parseDateTimeArgs;
  1927. exports.parseNumberArgs = parseNumberArgs;
  1928. exports.parseTranslateArgs = parseTranslateArgs;
  1929. exports.registerLocaleFallbacker = registerLocaleFallbacker;
  1930. exports.registerMessageCompiler = registerMessageCompiler;
  1931. exports.registerMessageResolver = registerMessageResolver;
  1932. exports.resolveLocale = resolveLocale;
  1933. exports.resolveValue = resolveValue;
  1934. exports.resolveWithKeyValue = resolveWithKeyValue;
  1935. exports.setAdditionalMeta = setAdditionalMeta;
  1936. exports.setDevToolsHook = setDevToolsHook;
  1937. exports.setFallbackContext = setFallbackContext;
  1938. exports.translate = translate;
  1939. exports.translateDevTools = translateDevTools;
  1940. exports.updateFallbackLocale = updateFallbackLocale;