@intlify/core-base 9.3.0-beta.2 → 9.3.0-beta.21

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