core-base.mjs 64 KB

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