@intlify/core 10.0.0-beta.5 → 10.0.0-rc.1

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