@intlify/core-base 11.1.2 → 12.0.0-alpha.2

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