0fa514947cbbb91670dcd5b43d98de88450f47e773fa0281e211ab530245d57df7901c0725ad1804247f81747b4e6727cf05bf08b6c42276b276246e207fd9 57 KB

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