@intlify/core-base 9.3.0-beta.17 → 9.3.0-beta.18

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