@intlify/core-base 9.3.0-beta.9 → 9.4.0

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