core-base.prod.cjs 56 KB

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