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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1706 +1,3216 @@
1
1
  /*!
2
- * core v9.3.0-beta.2
3
- * (c) 2022 kazuya kawaguchi
2
+ * core v9.3.0-beta.21
3
+ * (c) 2023 kazuya kawaguchi
4
4
  * Released under the MIT License.
5
5
  */
6
- /**
7
- * Original Utilities
8
- * written by kazuya kawaguchi
9
- */
10
- const inBrowser = typeof window !== 'undefined';
11
- let mark;
12
- let measure;
13
- {
14
- const perf = inBrowser && window.performance;
15
- if (perf &&
16
- perf.mark &&
17
- perf.measure &&
18
- perf.clearMarks &&
19
- perf.clearMeasures) {
20
- mark = (tag) => perf.mark(tag);
21
- measure = (name, startTag, endTag) => {
22
- perf.measure(name, startTag, endTag);
23
- perf.clearMarks(startTag);
24
- perf.clearMarks(endTag);
25
- };
26
- }
27
- }
28
- const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
29
- /* eslint-disable */
30
- function format(message, ...args) {
31
- if (args.length === 1 && isObject(args[0])) {
32
- args = args[0];
33
- }
34
- if (!args || !args.hasOwnProperty) {
35
- args = {};
36
- }
37
- return message.replace(RE_ARGS, (match, identifier) => {
38
- return args.hasOwnProperty(identifier) ? args[identifier] : '';
39
- });
40
- }
41
- const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
42
- const friendlyJSONstringify = (json) => JSON.stringify(json)
43
- .replace(/\u2028/g, '\\u2028')
44
- .replace(/\u2029/g, '\\u2029')
45
- .replace(/\u0027/g, '\\u0027');
46
- const isNumber = (val) => typeof val === 'number' && isFinite(val);
47
- const isDate = (val) => toTypeString(val) === '[object Date]';
48
- const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
49
- const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
50
- function warn(msg, err) {
51
- if (typeof console !== 'undefined') {
52
- console.warn(`[intlify] ` + msg);
53
- /* istanbul ignore if */
54
- if (err) {
55
- console.warn(err.stack);
56
- }
57
- }
58
- }
59
- const assign = Object.assign;
60
- function escapeHtml(rawText) {
61
- return rawText
62
- .replace(/</g, '&lt;')
63
- .replace(/>/g, '&gt;')
64
- .replace(/"/g, '&quot;')
65
- .replace(/'/g, '&apos;');
66
- }
67
- /* eslint-enable */
68
- /**
69
- * Useful Utilities By Evan you
70
- * Modified by kazuya kawaguchi
71
- * MIT License
72
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
73
- * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
74
- */
75
- const isArray = Array.isArray;
76
- const isFunction = (val) => typeof val === 'function';
77
- const isString = (val) => typeof val === 'string';
78
- const isBoolean = (val) => typeof val === 'boolean';
79
- const isObject = (val) => // eslint-disable-line
80
- val !== null && typeof val === 'object';
81
- const objectToString = Object.prototype.toString;
82
- const toTypeString = (value) => objectToString.call(value);
83
- const isPlainObject = (val) => toTypeString(val) === '[object Object]';
84
- // for converting list and named values to displayed strings.
85
- const toDisplayString = (val) => {
86
- return val == null
87
- ? ''
88
- : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
89
- ? JSON.stringify(val, null, 2)
90
- : String(val);
91
- };
92
- const RANGE = 2;
93
- function generateCodeFrame(source, start = 0, end = source.length) {
94
- const lines = source.split(/\r?\n/);
95
- let count = 0;
96
- const res = [];
97
- for (let i = 0; i < lines.length; i++) {
98
- count += lines[i].length + 1;
99
- if (count >= start) {
100
- for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
101
- if (j < 0 || j >= lines.length)
102
- continue;
103
- const line = j + 1;
104
- res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
105
- const lineLength = lines[j].length;
106
- if (j === i) {
107
- // push underline
108
- const pad = start - (count - lineLength) + 1;
109
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
110
- res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
111
- }
112
- else if (j > i) {
113
- if (end > count) {
114
- const length = Math.max(Math.min(end - count, lineLength), 1);
115
- res.push(` | ` + '^'.repeat(length));
116
- }
117
- count += lineLength + 1;
118
- }
119
- }
120
- break;
121
- }
122
- }
123
- return res.join('\n');
6
+ /**
7
+ * Original Utilities
8
+ * written by kazuya kawaguchi
9
+ */
10
+ const inBrowser = typeof window !== 'undefined';
11
+ let mark;
12
+ let measure;
13
+ {
14
+ const perf = inBrowser && window.performance;
15
+ if (perf &&
16
+ perf.mark &&
17
+ perf.measure &&
18
+ perf.clearMarks &&
19
+ // @ts-ignore browser compat
20
+ perf.clearMeasures) {
21
+ mark = (tag) => {
22
+ perf.mark(tag);
23
+ };
24
+ measure = (name, startTag, endTag) => {
25
+ perf.measure(name, startTag, endTag);
26
+ perf.clearMarks(startTag);
27
+ perf.clearMarks(endTag);
28
+ };
29
+ }
30
+ }
31
+ const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
32
+ /* eslint-disable */
33
+ function format$1(message, ...args) {
34
+ if (args.length === 1 && isObject(args[0])) {
35
+ args = args[0];
36
+ }
37
+ if (!args || !args.hasOwnProperty) {
38
+ args = {};
39
+ }
40
+ return message.replace(RE_ARGS, (match, identifier) => {
41
+ return args.hasOwnProperty(identifier) ? args[identifier] : '';
42
+ });
43
+ }
44
+ const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
45
+ const friendlyJSONstringify = (json) => JSON.stringify(json)
46
+ .replace(/\u2028/g, '\\u2028')
47
+ .replace(/\u2029/g, '\\u2029')
48
+ .replace(/\u0027/g, '\\u0027');
49
+ const isNumber = (val) => typeof val === 'number' && isFinite(val);
50
+ const isDate = (val) => toTypeString(val) === '[object Date]';
51
+ const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
52
+ const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
53
+ function warn(msg, err) {
54
+ if (typeof console !== 'undefined') {
55
+ console.warn(`[intlify] ` + msg);
56
+ /* istanbul ignore if */
57
+ if (err) {
58
+ console.warn(err.stack);
59
+ }
60
+ }
61
+ }
62
+ const assign = Object.assign;
63
+ function escapeHtml(rawText) {
64
+ return rawText
65
+ .replace(/</g, '&lt;')
66
+ .replace(/>/g, '&gt;')
67
+ .replace(/"/g, '&quot;')
68
+ .replace(/'/g, '&apos;');
69
+ }
70
+ /* eslint-enable */
71
+ /**
72
+ * Useful Utilities By Evan you
73
+ * Modified by kazuya kawaguchi
74
+ * MIT License
75
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
76
+ * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
77
+ */
78
+ const isArray = Array.isArray;
79
+ const isFunction = (val) => typeof val === 'function';
80
+ const isString = (val) => typeof val === 'string';
81
+ const isBoolean = (val) => typeof val === 'boolean';
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ const isObject = (val) => val !== null && typeof val === 'object';
84
+ const objectToString = Object.prototype.toString;
85
+ const toTypeString = (value) => objectToString.call(value);
86
+ const isPlainObject = (val) => {
87
+ if (!isObject(val))
88
+ return false;
89
+ const proto = Object.getPrototypeOf(val);
90
+ return proto === null || proto.constructor === Object;
91
+ };
92
+ // for converting list and named values to displayed strings.
93
+ const toDisplayString = (val) => {
94
+ return val == null
95
+ ? ''
96
+ : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
97
+ ? JSON.stringify(val, null, 2)
98
+ : String(val);
99
+ };
100
+ function join(items, separator = '') {
101
+ return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
102
+ }
103
+ const RANGE = 2;
104
+ function generateCodeFrame(source, start = 0, end = source.length) {
105
+ const lines = source.split(/\r?\n/);
106
+ let count = 0;
107
+ const res = [];
108
+ for (let i = 0; i < lines.length; i++) {
109
+ count += lines[i].length + 1;
110
+ if (count >= start) {
111
+ for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
112
+ if (j < 0 || j >= lines.length)
113
+ continue;
114
+ const line = j + 1;
115
+ res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
116
+ const lineLength = lines[j].length;
117
+ if (j === i) {
118
+ // push underline
119
+ const pad = start - (count - lineLength) + 1;
120
+ const length = Math.max(1, end > count ? lineLength - pad : end - start);
121
+ res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
122
+ }
123
+ else if (j > i) {
124
+ if (end > count) {
125
+ const length = Math.max(Math.min(end - count, lineLength), 1);
126
+ res.push(` | ` + '^'.repeat(length));
127
+ }
128
+ count += lineLength + 1;
129
+ }
130
+ }
131
+ break;
132
+ }
133
+ }
134
+ return res.join('\n');
124
135
  }
125
136
 
126
- const CompileErrorCodes = {
127
- // tokenizer error codes
128
- EXPECTED_TOKEN: 1,
129
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
130
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
131
- UNKNOWN_ESCAPE_SEQUENCE: 4,
132
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
133
- UNBALANCED_CLOSING_BRACE: 6,
134
- UNTERMINATED_CLOSING_BRACE: 7,
135
- EMPTY_PLACEHOLDER: 8,
136
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
137
- INVALID_LINKED_FORMAT: 10,
138
- // parser error codes
139
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
140
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
141
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
142
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
143
- // Special value for higher-order compilers to pick up the last code
144
- // to avoid collision of error codes. This should always be kept as the last
145
- // item.
146
- __EXTEND_POINT__: 15
147
- };
148
- /** @internal */
149
- const errorMessages$1 = {
150
- // tokenizer error messages
151
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
152
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
153
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
154
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
155
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
156
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
157
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
158
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
159
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
160
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
161
- // parser error messages
162
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
163
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
164
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
165
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
166
- };
167
- function createCompileError(code, loc, options = {}) {
168
- const { domain, messages, args } = options;
169
- const msg = format((messages || errorMessages$1)[code] || '', ...(args || []))
170
- ;
171
- const error = new SyntaxError(String(msg));
172
- error.code = code;
173
- if (loc) {
174
- error.location = loc;
175
- }
176
- error.domain = domain;
177
- return error;
137
+ function createPosition(line, column, offset) {
138
+ return { line, column, offset };
139
+ }
140
+ function createLocation(start, end, source) {
141
+ const loc = { start, end };
142
+ if (source != null) {
143
+ loc.source = source;
144
+ }
145
+ return loc;
146
+ }
147
+
148
+ const CompileErrorCodes = {
149
+ // tokenizer error codes
150
+ EXPECTED_TOKEN: 1,
151
+ INVALID_TOKEN_IN_PLACEHOLDER: 2,
152
+ UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
153
+ UNKNOWN_ESCAPE_SEQUENCE: 4,
154
+ INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
155
+ UNBALANCED_CLOSING_BRACE: 6,
156
+ UNTERMINATED_CLOSING_BRACE: 7,
157
+ EMPTY_PLACEHOLDER: 8,
158
+ NOT_ALLOW_NEST_PLACEHOLDER: 9,
159
+ INVALID_LINKED_FORMAT: 10,
160
+ // parser error codes
161
+ MUST_HAVE_MESSAGES_IN_PLURAL: 11,
162
+ UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
163
+ UNEXPECTED_EMPTY_LINKED_KEY: 13,
164
+ UNEXPECTED_LEXICAL_ANALYSIS: 14,
165
+ // Special value for higher-order compilers to pick up the last code
166
+ // to avoid collision of error codes. This should always be kept as the last
167
+ // item.
168
+ __EXTEND_POINT__: 15
169
+ };
170
+ /** @internal */
171
+ const errorMessages$1 = {
172
+ // tokenizer error messages
173
+ [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
174
+ [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
175
+ [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
176
+ [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
177
+ [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
178
+ [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
179
+ [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
180
+ [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
181
+ [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
182
+ [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
183
+ // parser error messages
184
+ [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
185
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
186
+ [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
187
+ [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
188
+ };
189
+ function createCompileError(code, loc, options = {}) {
190
+ const { domain, messages, args } = options;
191
+ const msg = format$1((messages || errorMessages$1)[code] || '', ...(args || []))
192
+ ;
193
+ const error = new SyntaxError(String(msg));
194
+ error.code = code;
195
+ if (loc) {
196
+ error.location = loc;
197
+ }
198
+ error.domain = domain;
199
+ return error;
200
+ }
201
+ /** @internal */
202
+ function defaultOnError(error) {
203
+ throw error;
178
204
  }
179
205
 
180
- const pathStateMachine = [];
181
- pathStateMachine[0 /* BEFORE_PATH */] = {
182
- ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
183
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
184
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
185
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
186
- };
187
- pathStateMachine[1 /* IN_PATH */] = {
188
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
189
- ["." /* DOT */]: [2 /* BEFORE_IDENT */],
190
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
191
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
192
- };
193
- pathStateMachine[2 /* BEFORE_IDENT */] = {
194
- ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
195
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
196
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
197
- };
198
- pathStateMachine[3 /* IN_IDENT */] = {
199
- ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
200
- ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
201
- ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
202
- ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
203
- ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
204
- ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
205
- };
206
- pathStateMachine[4 /* IN_SUB_PATH */] = {
207
- ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
208
- ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
209
- ["[" /* LEFT_BRACKET */]: [
210
- 4 /* IN_SUB_PATH */,
211
- 2 /* INC_SUB_PATH_DEPTH */
212
- ],
213
- ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
214
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
215
- ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
216
- };
217
- pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
218
- ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
219
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
220
- ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
221
- };
222
- pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
223
- ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
224
- ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
225
- ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
226
- };
227
- /**
228
- * Check if an expression is a literal value.
229
- */
230
- const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
231
- function isLiteral(exp) {
232
- return literalValueRE.test(exp);
233
- }
234
- /**
235
- * Strip quotes from a string
236
- */
237
- function stripQuotes(str) {
238
- const a = str.charCodeAt(0);
239
- const b = str.charCodeAt(str.length - 1);
240
- return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
241
- }
242
- /**
243
- * Determine the type of a character in a keypath.
244
- */
245
- function getPathCharType(ch) {
246
- if (ch === undefined || ch === null) {
247
- return "o" /* END_OF_FAIL */;
248
- }
249
- const code = ch.charCodeAt(0);
250
- switch (code) {
251
- case 0x5b: // [
252
- case 0x5d: // ]
253
- case 0x2e: // .
254
- case 0x22: // "
255
- case 0x27: // '
256
- return ch;
257
- case 0x5f: // _
258
- case 0x24: // $
259
- case 0x2d: // -
260
- return "i" /* IDENT */;
261
- case 0x09: // Tab (HT)
262
- case 0x0a: // Newline (LF)
263
- case 0x0d: // Return (CR)
264
- case 0xa0: // No-break space (NBSP)
265
- case 0xfeff: // Byte Order Mark (BOM)
266
- case 0x2028: // Line Separator (LS)
267
- case 0x2029: // Paragraph Separator (PS)
268
- return "w" /* WORKSPACE */;
269
- }
270
- return "i" /* IDENT */;
271
- }
272
- /**
273
- * Format a subPath, return its plain form if it is
274
- * a literal string or number. Otherwise prepend the
275
- * dynamic indicator (*).
276
- */
277
- function formatSubPath(path) {
278
- const trimmed = path.trim();
279
- // invalid leading 0
280
- if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
281
- return false;
282
- }
283
- return isLiteral(trimmed)
284
- ? stripQuotes(trimmed)
285
- : "*" /* ASTARISK */ + trimmed;
286
- }
287
- /**
288
- * Parse a string path into an array of segments
289
- */
290
- function parse(path) {
291
- const keys = [];
292
- let index = -1;
293
- let mode = 0 /* BEFORE_PATH */;
294
- let subPathDepth = 0;
295
- let c;
296
- let key; // eslint-disable-line
297
- let newChar;
298
- let type;
299
- let transition;
300
- let action;
301
- let typeMap;
302
- const actions = [];
303
- actions[0 /* APPEND */] = () => {
304
- if (key === undefined) {
305
- key = newChar;
306
- }
307
- else {
308
- key += newChar;
309
- }
310
- };
311
- actions[1 /* PUSH */] = () => {
312
- if (key !== undefined) {
313
- keys.push(key);
314
- key = undefined;
315
- }
316
- };
317
- actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
318
- actions[0 /* APPEND */]();
319
- subPathDepth++;
320
- };
321
- actions[3 /* PUSH_SUB_PATH */] = () => {
322
- if (subPathDepth > 0) {
323
- subPathDepth--;
324
- mode = 4 /* IN_SUB_PATH */;
325
- actions[0 /* APPEND */]();
326
- }
327
- else {
328
- subPathDepth = 0;
329
- if (key === undefined) {
330
- return false;
331
- }
332
- key = formatSubPath(key);
333
- if (key === false) {
334
- return false;
335
- }
336
- else {
337
- actions[1 /* PUSH */]();
338
- }
339
- }
340
- };
341
- function maybeUnescapeQuote() {
342
- const nextChar = path[index + 1];
343
- if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
344
- nextChar === "'" /* SINGLE_QUOTE */) ||
345
- (mode === 6 /* IN_DOUBLE_QUOTE */ &&
346
- nextChar === "\"" /* DOUBLE_QUOTE */)) {
347
- index++;
348
- newChar = '\\' + nextChar;
349
- actions[0 /* APPEND */]();
350
- return true;
351
- }
352
- }
353
- while (mode !== null) {
354
- index++;
355
- c = path[index];
356
- if (c === '\\' && maybeUnescapeQuote()) {
357
- continue;
358
- }
359
- type = getPathCharType(c);
360
- typeMap = pathStateMachine[mode];
361
- transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
362
- // check parse error
363
- if (transition === 8 /* ERROR */) {
364
- return;
365
- }
366
- mode = transition[0];
367
- if (transition[1] !== undefined) {
368
- action = actions[transition[1]];
369
- if (action) {
370
- newChar = c;
371
- if (action() === false) {
372
- return;
373
- }
374
- }
375
- }
376
- // check parse finish
377
- if (mode === 7 /* AFTER_PATH */) {
378
- return keys;
379
- }
380
- }
381
- }
382
- // path token cache
383
- const cache = new Map();
384
- /**
385
- * key-value message resolver
386
- *
387
- * @remarks
388
- * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
389
- *
390
- * @param obj - A target object to be resolved with path
391
- * @param path - A {@link Path | path} to resolve the value of message
392
- *
393
- * @returns A resolved {@link PathValue | path value}
394
- *
395
- * @VueI18nGeneral
396
- */
397
- function resolveWithKeyValue(obj, path) {
398
- return isObject(obj) ? obj[path] : null;
399
- }
400
- /**
401
- * message resolver
402
- *
403
- * @remarks
404
- * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
405
- *
406
- * @param obj - A target object to be resolved with path
407
- * @param path - A {@link Path | path} to resolve the value of message
408
- *
409
- * @returns A resolved {@link PathValue | path value}
410
- *
411
- * @VueI18nGeneral
412
- */
413
- function resolveValue(obj, path) {
414
- // check object
415
- if (!isObject(obj)) {
416
- return null;
417
- }
418
- // parse path
419
- let hit = cache.get(path);
420
- if (!hit) {
421
- hit = parse(path);
422
- if (hit) {
423
- cache.set(path, hit);
424
- }
425
- }
426
- // check hit
427
- if (!hit) {
428
- return null;
429
- }
430
- // resolve path value
431
- const len = hit.length;
432
- let last = obj;
433
- let i = 0;
434
- while (i < len) {
435
- const val = last[hit[i]];
436
- if (val === undefined) {
437
- return null;
438
- }
439
- last = val;
440
- i++;
441
- }
442
- return last;
206
+ const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
207
+ const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
208
+
209
+ const CHAR_SP = ' ';
210
+ const CHAR_CR = '\r';
211
+ const CHAR_LF = '\n';
212
+ const CHAR_LS = String.fromCharCode(0x2028);
213
+ const CHAR_PS = String.fromCharCode(0x2029);
214
+ function createScanner(str) {
215
+ const _buf = str;
216
+ let _index = 0;
217
+ let _line = 1;
218
+ let _column = 1;
219
+ let _peekOffset = 0;
220
+ const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
221
+ const isLF = (index) => _buf[index] === CHAR_LF;
222
+ const isPS = (index) => _buf[index] === CHAR_PS;
223
+ const isLS = (index) => _buf[index] === CHAR_LS;
224
+ const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
225
+ const index = () => _index;
226
+ const line = () => _line;
227
+ const column = () => _column;
228
+ const peekOffset = () => _peekOffset;
229
+ const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
230
+ const currentChar = () => charAt(_index);
231
+ const currentPeek = () => charAt(_index + _peekOffset);
232
+ function next() {
233
+ _peekOffset = 0;
234
+ if (isLineEnd(_index)) {
235
+ _line++;
236
+ _column = 0;
237
+ }
238
+ if (isCRLF(_index)) {
239
+ _index++;
240
+ }
241
+ _index++;
242
+ _column++;
243
+ return _buf[_index];
244
+ }
245
+ function peek() {
246
+ if (isCRLF(_index + _peekOffset)) {
247
+ _peekOffset++;
248
+ }
249
+ _peekOffset++;
250
+ return _buf[_index + _peekOffset];
251
+ }
252
+ function reset() {
253
+ _index = 0;
254
+ _line = 1;
255
+ _column = 1;
256
+ _peekOffset = 0;
257
+ }
258
+ function resetPeek(offset = 0) {
259
+ _peekOffset = offset;
260
+ }
261
+ function skipToPeek() {
262
+ const target = _index + _peekOffset;
263
+ // eslint-disable-next-line no-unmodified-loop-condition
264
+ while (target !== _index) {
265
+ next();
266
+ }
267
+ _peekOffset = 0;
268
+ }
269
+ return {
270
+ index,
271
+ line,
272
+ column,
273
+ peekOffset,
274
+ charAt,
275
+ currentChar,
276
+ currentPeek,
277
+ next,
278
+ peek,
279
+ reset,
280
+ resetPeek,
281
+ skipToPeek
282
+ };
283
+ }
284
+
285
+ const EOF = undefined;
286
+ const LITERAL_DELIMITER = "'";
287
+ const ERROR_DOMAIN$1 = 'tokenizer';
288
+ function createTokenizer(source, options = {}) {
289
+ const location = options.location !== false;
290
+ const _scnr = createScanner(source);
291
+ const currentOffset = () => _scnr.index();
292
+ const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
293
+ const _initLoc = currentPosition();
294
+ const _initOffset = currentOffset();
295
+ const _context = {
296
+ currentType: 14 /* TokenTypes.EOF */,
297
+ offset: _initOffset,
298
+ startLoc: _initLoc,
299
+ endLoc: _initLoc,
300
+ lastType: 14 /* TokenTypes.EOF */,
301
+ lastOffset: _initOffset,
302
+ lastStartLoc: _initLoc,
303
+ lastEndLoc: _initLoc,
304
+ braceNest: 0,
305
+ inLinked: false,
306
+ text: ''
307
+ };
308
+ const context = () => _context;
309
+ const { onError } = options;
310
+ function emitError(code, pos, offset, ...args) {
311
+ const ctx = context();
312
+ pos.column += offset;
313
+ pos.offset += offset;
314
+ if (onError) {
315
+ const loc = location ? createLocation(ctx.startLoc, pos) : null;
316
+ const err = createCompileError(code, loc, {
317
+ domain: ERROR_DOMAIN$1,
318
+ args
319
+ });
320
+ onError(err);
321
+ }
322
+ }
323
+ function getToken(context, type, value) {
324
+ context.endLoc = currentPosition();
325
+ context.currentType = type;
326
+ const token = { type };
327
+ if (location) {
328
+ token.loc = createLocation(context.startLoc, context.endLoc);
329
+ }
330
+ if (value != null) {
331
+ token.value = value;
332
+ }
333
+ return token;
334
+ }
335
+ const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
336
+ function eat(scnr, ch) {
337
+ if (scnr.currentChar() === ch) {
338
+ scnr.next();
339
+ return ch;
340
+ }
341
+ else {
342
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
343
+ return '';
344
+ }
345
+ }
346
+ function peekSpaces(scnr) {
347
+ let buf = '';
348
+ while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
349
+ buf += scnr.currentPeek();
350
+ scnr.peek();
351
+ }
352
+ return buf;
353
+ }
354
+ function skipSpaces(scnr) {
355
+ const buf = peekSpaces(scnr);
356
+ scnr.skipToPeek();
357
+ return buf;
358
+ }
359
+ function isIdentifierStart(ch) {
360
+ if (ch === EOF) {
361
+ return false;
362
+ }
363
+ const cc = ch.charCodeAt(0);
364
+ return ((cc >= 97 && cc <= 122) || // a-z
365
+ (cc >= 65 && cc <= 90) || // A-Z
366
+ cc === 95 // _
367
+ );
368
+ }
369
+ function isNumberStart(ch) {
370
+ if (ch === EOF) {
371
+ return false;
372
+ }
373
+ const cc = ch.charCodeAt(0);
374
+ return cc >= 48 && cc <= 57; // 0-9
375
+ }
376
+ function isNamedIdentifierStart(scnr, context) {
377
+ const { currentType } = context;
378
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
379
+ return false;
380
+ }
381
+ peekSpaces(scnr);
382
+ const ret = isIdentifierStart(scnr.currentPeek());
383
+ scnr.resetPeek();
384
+ return ret;
385
+ }
386
+ function isListIdentifierStart(scnr, context) {
387
+ const { currentType } = context;
388
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
389
+ return false;
390
+ }
391
+ peekSpaces(scnr);
392
+ const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
393
+ const ret = isNumberStart(ch);
394
+ scnr.resetPeek();
395
+ return ret;
396
+ }
397
+ function isLiteralStart(scnr, context) {
398
+ const { currentType } = context;
399
+ if (currentType !== 2 /* TokenTypes.BraceLeft */) {
400
+ return false;
401
+ }
402
+ peekSpaces(scnr);
403
+ const ret = scnr.currentPeek() === LITERAL_DELIMITER;
404
+ scnr.resetPeek();
405
+ return ret;
406
+ }
407
+ function isLinkedDotStart(scnr, context) {
408
+ const { currentType } = context;
409
+ if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
410
+ return false;
411
+ }
412
+ peekSpaces(scnr);
413
+ const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
414
+ scnr.resetPeek();
415
+ return ret;
416
+ }
417
+ function isLinkedModifierStart(scnr, context) {
418
+ const { currentType } = context;
419
+ if (currentType !== 9 /* TokenTypes.LinkedDot */) {
420
+ return false;
421
+ }
422
+ peekSpaces(scnr);
423
+ const ret = isIdentifierStart(scnr.currentPeek());
424
+ scnr.resetPeek();
425
+ return ret;
426
+ }
427
+ function isLinkedDelimiterStart(scnr, context) {
428
+ const { currentType } = context;
429
+ if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
430
+ currentType === 12 /* TokenTypes.LinkedModifier */)) {
431
+ return false;
432
+ }
433
+ peekSpaces(scnr);
434
+ const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
435
+ scnr.resetPeek();
436
+ return ret;
437
+ }
438
+ function isLinkedReferStart(scnr, context) {
439
+ const { currentType } = context;
440
+ if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
441
+ return false;
442
+ }
443
+ const fn = () => {
444
+ const ch = scnr.currentPeek();
445
+ if (ch === "{" /* TokenChars.BraceLeft */) {
446
+ return isIdentifierStart(scnr.peek());
447
+ }
448
+ else if (ch === "@" /* TokenChars.LinkedAlias */ ||
449
+ ch === "%" /* TokenChars.Modulo */ ||
450
+ ch === "|" /* TokenChars.Pipe */ ||
451
+ ch === ":" /* TokenChars.LinkedDelimiter */ ||
452
+ ch === "." /* TokenChars.LinkedDot */ ||
453
+ ch === CHAR_SP ||
454
+ !ch) {
455
+ return false;
456
+ }
457
+ else if (ch === CHAR_LF) {
458
+ scnr.peek();
459
+ return fn();
460
+ }
461
+ else {
462
+ // other characters
463
+ return isIdentifierStart(ch);
464
+ }
465
+ };
466
+ const ret = fn();
467
+ scnr.resetPeek();
468
+ return ret;
469
+ }
470
+ function isPluralStart(scnr) {
471
+ peekSpaces(scnr);
472
+ const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
473
+ scnr.resetPeek();
474
+ return ret;
475
+ }
476
+ function detectModuloStart(scnr) {
477
+ const spaces = peekSpaces(scnr);
478
+ const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
479
+ scnr.peek() === "{" /* TokenChars.BraceLeft */;
480
+ scnr.resetPeek();
481
+ return {
482
+ isModulo: ret,
483
+ hasSpace: spaces.length > 0
484
+ };
485
+ }
486
+ function isTextStart(scnr, reset = true) {
487
+ const fn = (hasSpace = false, prev = '', detectModulo = false) => {
488
+ const ch = scnr.currentPeek();
489
+ if (ch === "{" /* TokenChars.BraceLeft */) {
490
+ return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
491
+ }
492
+ else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
493
+ return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
494
+ }
495
+ else if (ch === "%" /* TokenChars.Modulo */) {
496
+ scnr.peek();
497
+ return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
498
+ }
499
+ else if (ch === "|" /* TokenChars.Pipe */) {
500
+ return prev === "%" /* TokenChars.Modulo */ || detectModulo
501
+ ? true
502
+ : !(prev === CHAR_SP || prev === CHAR_LF);
503
+ }
504
+ else if (ch === CHAR_SP) {
505
+ scnr.peek();
506
+ return fn(true, CHAR_SP, detectModulo);
507
+ }
508
+ else if (ch === CHAR_LF) {
509
+ scnr.peek();
510
+ return fn(true, CHAR_LF, detectModulo);
511
+ }
512
+ else {
513
+ return true;
514
+ }
515
+ };
516
+ const ret = fn();
517
+ reset && scnr.resetPeek();
518
+ return ret;
519
+ }
520
+ function takeChar(scnr, fn) {
521
+ const ch = scnr.currentChar();
522
+ if (ch === EOF) {
523
+ return EOF;
524
+ }
525
+ if (fn(ch)) {
526
+ scnr.next();
527
+ return ch;
528
+ }
529
+ return null;
530
+ }
531
+ function takeIdentifierChar(scnr) {
532
+ const closure = (ch) => {
533
+ const cc = ch.charCodeAt(0);
534
+ return ((cc >= 97 && cc <= 122) || // a-z
535
+ (cc >= 65 && cc <= 90) || // A-Z
536
+ (cc >= 48 && cc <= 57) || // 0-9
537
+ cc === 95 || // _
538
+ cc === 36 // $
539
+ );
540
+ };
541
+ return takeChar(scnr, closure);
542
+ }
543
+ function takeDigit(scnr) {
544
+ const closure = (ch) => {
545
+ const cc = ch.charCodeAt(0);
546
+ return cc >= 48 && cc <= 57; // 0-9
547
+ };
548
+ return takeChar(scnr, closure);
549
+ }
550
+ function takeHexDigit(scnr) {
551
+ const closure = (ch) => {
552
+ const cc = ch.charCodeAt(0);
553
+ return ((cc >= 48 && cc <= 57) || // 0-9
554
+ (cc >= 65 && cc <= 70) || // A-F
555
+ (cc >= 97 && cc <= 102)); // a-f
556
+ };
557
+ return takeChar(scnr, closure);
558
+ }
559
+ function getDigits(scnr) {
560
+ let ch = '';
561
+ let num = '';
562
+ while ((ch = takeDigit(scnr))) {
563
+ num += ch;
564
+ }
565
+ return num;
566
+ }
567
+ function readModulo(scnr) {
568
+ skipSpaces(scnr);
569
+ const ch = scnr.currentChar();
570
+ if (ch !== "%" /* TokenChars.Modulo */) {
571
+ emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
572
+ }
573
+ scnr.next();
574
+ return "%" /* TokenChars.Modulo */;
575
+ }
576
+ function readText(scnr) {
577
+ let buf = '';
578
+ while (true) {
579
+ const ch = scnr.currentChar();
580
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
581
+ ch === "}" /* TokenChars.BraceRight */ ||
582
+ ch === "@" /* TokenChars.LinkedAlias */ ||
583
+ ch === "|" /* TokenChars.Pipe */ ||
584
+ !ch) {
585
+ break;
586
+ }
587
+ else if (ch === "%" /* TokenChars.Modulo */) {
588
+ if (isTextStart(scnr)) {
589
+ buf += ch;
590
+ scnr.next();
591
+ }
592
+ else {
593
+ break;
594
+ }
595
+ }
596
+ else if (ch === CHAR_SP || ch === CHAR_LF) {
597
+ if (isTextStart(scnr)) {
598
+ buf += ch;
599
+ scnr.next();
600
+ }
601
+ else if (isPluralStart(scnr)) {
602
+ break;
603
+ }
604
+ else {
605
+ buf += ch;
606
+ scnr.next();
607
+ }
608
+ }
609
+ else {
610
+ buf += ch;
611
+ scnr.next();
612
+ }
613
+ }
614
+ return buf;
615
+ }
616
+ function readNamedIdentifier(scnr) {
617
+ skipSpaces(scnr);
618
+ let ch = '';
619
+ let name = '';
620
+ while ((ch = takeIdentifierChar(scnr))) {
621
+ name += ch;
622
+ }
623
+ if (scnr.currentChar() === EOF) {
624
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
625
+ }
626
+ return name;
627
+ }
628
+ function readListIdentifier(scnr) {
629
+ skipSpaces(scnr);
630
+ let value = '';
631
+ if (scnr.currentChar() === '-') {
632
+ scnr.next();
633
+ value += `-${getDigits(scnr)}`;
634
+ }
635
+ else {
636
+ value += getDigits(scnr);
637
+ }
638
+ if (scnr.currentChar() === EOF) {
639
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
640
+ }
641
+ return value;
642
+ }
643
+ function readLiteral(scnr) {
644
+ skipSpaces(scnr);
645
+ eat(scnr, `\'`);
646
+ let ch = '';
647
+ let literal = '';
648
+ const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
649
+ while ((ch = takeChar(scnr, fn))) {
650
+ if (ch === '\\') {
651
+ literal += readEscapeSequence(scnr);
652
+ }
653
+ else {
654
+ literal += ch;
655
+ }
656
+ }
657
+ const current = scnr.currentChar();
658
+ if (current === CHAR_LF || current === EOF) {
659
+ emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
660
+ // TODO: Is it correct really?
661
+ if (current === CHAR_LF) {
662
+ scnr.next();
663
+ eat(scnr, `\'`);
664
+ }
665
+ return literal;
666
+ }
667
+ eat(scnr, `\'`);
668
+ return literal;
669
+ }
670
+ function readEscapeSequence(scnr) {
671
+ const ch = scnr.currentChar();
672
+ switch (ch) {
673
+ case '\\':
674
+ case `\'`:
675
+ scnr.next();
676
+ return `\\${ch}`;
677
+ case 'u':
678
+ return readUnicodeEscapeSequence(scnr, ch, 4);
679
+ case 'U':
680
+ return readUnicodeEscapeSequence(scnr, ch, 6);
681
+ default:
682
+ emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
683
+ return '';
684
+ }
685
+ }
686
+ function readUnicodeEscapeSequence(scnr, unicode, digits) {
687
+ eat(scnr, unicode);
688
+ let sequence = '';
689
+ for (let i = 0; i < digits; i++) {
690
+ const ch = takeHexDigit(scnr);
691
+ if (!ch) {
692
+ emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
693
+ break;
694
+ }
695
+ sequence += ch;
696
+ }
697
+ return `\\${unicode}${sequence}`;
698
+ }
699
+ function readInvalidIdentifier(scnr) {
700
+ skipSpaces(scnr);
701
+ let ch = '';
702
+ let identifiers = '';
703
+ const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
704
+ ch !== "}" /* TokenChars.BraceRight */ &&
705
+ ch !== CHAR_SP &&
706
+ ch !== CHAR_LF;
707
+ while ((ch = takeChar(scnr, closure))) {
708
+ identifiers += ch;
709
+ }
710
+ return identifiers;
711
+ }
712
+ function readLinkedModifier(scnr) {
713
+ let ch = '';
714
+ let name = '';
715
+ while ((ch = takeIdentifierChar(scnr))) {
716
+ name += ch;
717
+ }
718
+ return name;
719
+ }
720
+ function readLinkedRefer(scnr) {
721
+ const fn = (detect = false, buf) => {
722
+ const ch = scnr.currentChar();
723
+ if (ch === "{" /* TokenChars.BraceLeft */ ||
724
+ ch === "%" /* TokenChars.Modulo */ ||
725
+ ch === "@" /* TokenChars.LinkedAlias */ ||
726
+ ch === "|" /* TokenChars.Pipe */ ||
727
+ !ch) {
728
+ return buf;
729
+ }
730
+ else if (ch === CHAR_SP) {
731
+ return buf;
732
+ }
733
+ else if (ch === CHAR_LF) {
734
+ buf += ch;
735
+ scnr.next();
736
+ return fn(detect, buf);
737
+ }
738
+ else {
739
+ buf += ch;
740
+ scnr.next();
741
+ return fn(true, buf);
742
+ }
743
+ };
744
+ return fn(false, '');
745
+ }
746
+ function readPlural(scnr) {
747
+ skipSpaces(scnr);
748
+ const plural = eat(scnr, "|" /* TokenChars.Pipe */);
749
+ skipSpaces(scnr);
750
+ return plural;
751
+ }
752
+ // TODO: We need refactoring of token parsing ...
753
+ function readTokenInPlaceholder(scnr, context) {
754
+ let token = null;
755
+ const ch = scnr.currentChar();
756
+ switch (ch) {
757
+ case "{" /* TokenChars.BraceLeft */:
758
+ if (context.braceNest >= 1) {
759
+ emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
760
+ }
761
+ scnr.next();
762
+ token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
763
+ skipSpaces(scnr);
764
+ context.braceNest++;
765
+ return token;
766
+ case "}" /* TokenChars.BraceRight */:
767
+ if (context.braceNest > 0 &&
768
+ context.currentType === 2 /* TokenTypes.BraceLeft */) {
769
+ emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
770
+ }
771
+ scnr.next();
772
+ token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
773
+ context.braceNest--;
774
+ context.braceNest > 0 && skipSpaces(scnr);
775
+ if (context.inLinked && context.braceNest === 0) {
776
+ context.inLinked = false;
777
+ }
778
+ return token;
779
+ case "@" /* TokenChars.LinkedAlias */:
780
+ if (context.braceNest > 0) {
781
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
782
+ }
783
+ token = readTokenInLinked(scnr, context) || getEndToken(context);
784
+ context.braceNest = 0;
785
+ return token;
786
+ default:
787
+ let validNamedIdentifier = true;
788
+ let validListIdentifier = true;
789
+ let validLiteral = true;
790
+ if (isPluralStart(scnr)) {
791
+ if (context.braceNest > 0) {
792
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
793
+ }
794
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
795
+ // reset
796
+ context.braceNest = 0;
797
+ context.inLinked = false;
798
+ return token;
799
+ }
800
+ if (context.braceNest > 0 &&
801
+ (context.currentType === 5 /* TokenTypes.Named */ ||
802
+ context.currentType === 6 /* TokenTypes.List */ ||
803
+ context.currentType === 7 /* TokenTypes.Literal */)) {
804
+ emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
805
+ context.braceNest = 0;
806
+ return readToken(scnr, context);
807
+ }
808
+ if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
809
+ token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
810
+ skipSpaces(scnr);
811
+ return token;
812
+ }
813
+ if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
814
+ token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
815
+ skipSpaces(scnr);
816
+ return token;
817
+ }
818
+ if ((validLiteral = isLiteralStart(scnr, context))) {
819
+ token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
820
+ skipSpaces(scnr);
821
+ return token;
822
+ }
823
+ if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
824
+ // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
825
+ token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
826
+ emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
827
+ skipSpaces(scnr);
828
+ return token;
829
+ }
830
+ break;
831
+ }
832
+ return token;
833
+ }
834
+ // TODO: We need refactoring of token parsing ...
835
+ function readTokenInLinked(scnr, context) {
836
+ const { currentType } = context;
837
+ let token = null;
838
+ const ch = scnr.currentChar();
839
+ if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
840
+ currentType === 9 /* TokenTypes.LinkedDot */ ||
841
+ currentType === 12 /* TokenTypes.LinkedModifier */ ||
842
+ currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
843
+ (ch === CHAR_LF || ch === CHAR_SP)) {
844
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
845
+ }
846
+ switch (ch) {
847
+ case "@" /* TokenChars.LinkedAlias */:
848
+ scnr.next();
849
+ token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
850
+ context.inLinked = true;
851
+ return token;
852
+ case "." /* TokenChars.LinkedDot */:
853
+ skipSpaces(scnr);
854
+ scnr.next();
855
+ return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
856
+ case ":" /* TokenChars.LinkedDelimiter */:
857
+ skipSpaces(scnr);
858
+ scnr.next();
859
+ return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
860
+ default:
861
+ if (isPluralStart(scnr)) {
862
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
863
+ // reset
864
+ context.braceNest = 0;
865
+ context.inLinked = false;
866
+ return token;
867
+ }
868
+ if (isLinkedDotStart(scnr, context) ||
869
+ isLinkedDelimiterStart(scnr, context)) {
870
+ skipSpaces(scnr);
871
+ return readTokenInLinked(scnr, context);
872
+ }
873
+ if (isLinkedModifierStart(scnr, context)) {
874
+ skipSpaces(scnr);
875
+ return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
876
+ }
877
+ if (isLinkedReferStart(scnr, context)) {
878
+ skipSpaces(scnr);
879
+ if (ch === "{" /* TokenChars.BraceLeft */) {
880
+ // scan the placeholder
881
+ return readTokenInPlaceholder(scnr, context) || token;
882
+ }
883
+ else {
884
+ return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
885
+ }
886
+ }
887
+ if (currentType === 8 /* TokenTypes.LinkedAlias */) {
888
+ emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
889
+ }
890
+ context.braceNest = 0;
891
+ context.inLinked = false;
892
+ return readToken(scnr, context);
893
+ }
894
+ }
895
+ // TODO: We need refactoring of token parsing ...
896
+ function readToken(scnr, context) {
897
+ let token = { type: 14 /* TokenTypes.EOF */ };
898
+ if (context.braceNest > 0) {
899
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
900
+ }
901
+ if (context.inLinked) {
902
+ return readTokenInLinked(scnr, context) || getEndToken(context);
903
+ }
904
+ const ch = scnr.currentChar();
905
+ switch (ch) {
906
+ case "{" /* TokenChars.BraceLeft */:
907
+ return readTokenInPlaceholder(scnr, context) || getEndToken(context);
908
+ case "}" /* TokenChars.BraceRight */:
909
+ emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
910
+ scnr.next();
911
+ return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
912
+ case "@" /* TokenChars.LinkedAlias */:
913
+ return readTokenInLinked(scnr, context) || getEndToken(context);
914
+ default:
915
+ if (isPluralStart(scnr)) {
916
+ token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
917
+ // reset
918
+ context.braceNest = 0;
919
+ context.inLinked = false;
920
+ return token;
921
+ }
922
+ const { isModulo, hasSpace } = detectModuloStart(scnr);
923
+ if (isModulo) {
924
+ return hasSpace
925
+ ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
926
+ : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
927
+ }
928
+ if (isTextStart(scnr)) {
929
+ return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
930
+ }
931
+ break;
932
+ }
933
+ return token;
934
+ }
935
+ function nextToken() {
936
+ const { currentType, offset, startLoc, endLoc } = _context;
937
+ _context.lastType = currentType;
938
+ _context.lastOffset = offset;
939
+ _context.lastStartLoc = startLoc;
940
+ _context.lastEndLoc = endLoc;
941
+ _context.offset = currentOffset();
942
+ _context.startLoc = currentPosition();
943
+ if (_scnr.currentChar() === EOF) {
944
+ return getToken(_context, 14 /* TokenTypes.EOF */);
945
+ }
946
+ return readToken(_scnr, _context);
947
+ }
948
+ return {
949
+ nextToken,
950
+ currentOffset,
951
+ currentPosition,
952
+ context
953
+ };
954
+ }
955
+
956
+ const ERROR_DOMAIN = 'parser';
957
+ // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
958
+ const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
959
+ function fromEscapeSequence(match, codePoint4, codePoint6) {
960
+ switch (match) {
961
+ case `\\\\`:
962
+ return `\\`;
963
+ case `\\\'`:
964
+ return `\'`;
965
+ default: {
966
+ const codePoint = parseInt(codePoint4 || codePoint6, 16);
967
+ if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
968
+ return String.fromCodePoint(codePoint);
969
+ }
970
+ // invalid ...
971
+ // Replace them with U+FFFD REPLACEMENT CHARACTER.
972
+ return '�';
973
+ }
974
+ }
975
+ }
976
+ function createParser(options = {}) {
977
+ const location = options.location !== false;
978
+ const { onError } = options;
979
+ function emitError(tokenzer, code, start, offset, ...args) {
980
+ const end = tokenzer.currentPosition();
981
+ end.offset += offset;
982
+ end.column += offset;
983
+ if (onError) {
984
+ const loc = location ? createLocation(start, end) : null;
985
+ const err = createCompileError(code, loc, {
986
+ domain: ERROR_DOMAIN,
987
+ args
988
+ });
989
+ onError(err);
990
+ }
991
+ }
992
+ function startNode(type, offset, loc) {
993
+ const node = { type };
994
+ if (location) {
995
+ node.start = offset;
996
+ node.end = offset;
997
+ node.loc = { start: loc, end: loc };
998
+ }
999
+ return node;
1000
+ }
1001
+ function endNode(node, offset, pos, type) {
1002
+ if (type) {
1003
+ node.type = type;
1004
+ }
1005
+ if (location) {
1006
+ node.end = offset;
1007
+ if (node.loc) {
1008
+ node.loc.end = pos;
1009
+ }
1010
+ }
1011
+ }
1012
+ function parseText(tokenizer, value) {
1013
+ const context = tokenizer.context();
1014
+ const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
1015
+ node.value = value;
1016
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1017
+ return node;
1018
+ }
1019
+ function parseList(tokenizer, index) {
1020
+ const context = tokenizer.context();
1021
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1022
+ const node = startNode(5 /* NodeTypes.List */, offset, loc);
1023
+ node.index = parseInt(index, 10);
1024
+ tokenizer.nextToken(); // skip brach right
1025
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1026
+ return node;
1027
+ }
1028
+ function parseNamed(tokenizer, key) {
1029
+ const context = tokenizer.context();
1030
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1031
+ const node = startNode(4 /* NodeTypes.Named */, offset, loc);
1032
+ node.key = key;
1033
+ tokenizer.nextToken(); // skip brach right
1034
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1035
+ return node;
1036
+ }
1037
+ function parseLiteral(tokenizer, value) {
1038
+ const context = tokenizer.context();
1039
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
1040
+ const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
1041
+ node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
1042
+ tokenizer.nextToken(); // skip brach right
1043
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1044
+ return node;
1045
+ }
1046
+ function parseLinkedModifier(tokenizer) {
1047
+ const token = tokenizer.nextToken();
1048
+ const context = tokenizer.context();
1049
+ const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
1050
+ const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
1051
+ if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
1052
+ // empty modifier
1053
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
1054
+ node.value = '';
1055
+ endNode(node, offset, loc);
1056
+ return {
1057
+ nextConsumeToken: token,
1058
+ node
1059
+ };
1060
+ }
1061
+ // check token
1062
+ if (token.value == null) {
1063
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1064
+ }
1065
+ node.value = token.value || '';
1066
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1067
+ return {
1068
+ node
1069
+ };
1070
+ }
1071
+ function parseLinkedKey(tokenizer, value) {
1072
+ const context = tokenizer.context();
1073
+ const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
1074
+ node.value = value;
1075
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1076
+ return node;
1077
+ }
1078
+ function parseLinked(tokenizer) {
1079
+ const context = tokenizer.context();
1080
+ const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
1081
+ let token = tokenizer.nextToken();
1082
+ if (token.type === 9 /* TokenTypes.LinkedDot */) {
1083
+ const parsed = parseLinkedModifier(tokenizer);
1084
+ linkedNode.modifier = parsed.node;
1085
+ token = parsed.nextConsumeToken || tokenizer.nextToken();
1086
+ }
1087
+ // asset check token
1088
+ if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
1089
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1090
+ }
1091
+ token = tokenizer.nextToken();
1092
+ // skip brace left
1093
+ if (token.type === 2 /* TokenTypes.BraceLeft */) {
1094
+ token = tokenizer.nextToken();
1095
+ }
1096
+ switch (token.type) {
1097
+ case 11 /* TokenTypes.LinkedKey */:
1098
+ if (token.value == null) {
1099
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1100
+ }
1101
+ linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
1102
+ break;
1103
+ case 5 /* TokenTypes.Named */:
1104
+ if (token.value == null) {
1105
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1106
+ }
1107
+ linkedNode.key = parseNamed(tokenizer, token.value || '');
1108
+ break;
1109
+ case 6 /* TokenTypes.List */:
1110
+ if (token.value == null) {
1111
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1112
+ }
1113
+ linkedNode.key = parseList(tokenizer, token.value || '');
1114
+ break;
1115
+ case 7 /* TokenTypes.Literal */:
1116
+ if (token.value == null) {
1117
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1118
+ }
1119
+ linkedNode.key = parseLiteral(tokenizer, token.value || '');
1120
+ break;
1121
+ default:
1122
+ // empty key
1123
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
1124
+ const nextContext = tokenizer.context();
1125
+ const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
1126
+ emptyLinkedKeyNode.value = '';
1127
+ endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
1128
+ linkedNode.key = emptyLinkedKeyNode;
1129
+ endNode(linkedNode, nextContext.offset, nextContext.startLoc);
1130
+ return {
1131
+ nextConsumeToken: token,
1132
+ node: linkedNode
1133
+ };
1134
+ }
1135
+ endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1136
+ return {
1137
+ node: linkedNode
1138
+ };
1139
+ }
1140
+ function parseMessage(tokenizer) {
1141
+ const context = tokenizer.context();
1142
+ const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1143
+ ? tokenizer.currentOffset()
1144
+ : context.offset;
1145
+ const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1146
+ ? context.endLoc
1147
+ : context.startLoc;
1148
+ const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1149
+ node.items = [];
1150
+ let nextToken = null;
1151
+ do {
1152
+ const token = nextToken || tokenizer.nextToken();
1153
+ nextToken = null;
1154
+ switch (token.type) {
1155
+ case 0 /* TokenTypes.Text */:
1156
+ if (token.value == null) {
1157
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1158
+ }
1159
+ node.items.push(parseText(tokenizer, token.value || ''));
1160
+ break;
1161
+ case 6 /* TokenTypes.List */:
1162
+ if (token.value == null) {
1163
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1164
+ }
1165
+ node.items.push(parseList(tokenizer, token.value || ''));
1166
+ break;
1167
+ case 5 /* TokenTypes.Named */:
1168
+ if (token.value == null) {
1169
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1170
+ }
1171
+ node.items.push(parseNamed(tokenizer, token.value || ''));
1172
+ break;
1173
+ case 7 /* TokenTypes.Literal */:
1174
+ if (token.value == null) {
1175
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1176
+ }
1177
+ node.items.push(parseLiteral(tokenizer, token.value || ''));
1178
+ break;
1179
+ case 8 /* TokenTypes.LinkedAlias */:
1180
+ const parsed = parseLinked(tokenizer);
1181
+ node.items.push(parsed.node);
1182
+ nextToken = parsed.nextConsumeToken || null;
1183
+ break;
1184
+ }
1185
+ } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
1186
+ context.currentType !== 1 /* TokenTypes.Pipe */);
1187
+ // adjust message node loc
1188
+ const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1189
+ ? context.lastOffset
1190
+ : tokenizer.currentOffset();
1191
+ const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1192
+ ? context.lastEndLoc
1193
+ : tokenizer.currentPosition();
1194
+ endNode(node, endOffset, endLoc);
1195
+ return node;
1196
+ }
1197
+ function parsePlural(tokenizer, offset, loc, msgNode) {
1198
+ const context = tokenizer.context();
1199
+ let hasEmptyMessage = msgNode.items.length === 0;
1200
+ const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1201
+ node.cases = [];
1202
+ node.cases.push(msgNode);
1203
+ do {
1204
+ const msg = parseMessage(tokenizer);
1205
+ if (!hasEmptyMessage) {
1206
+ hasEmptyMessage = msg.items.length === 0;
1207
+ }
1208
+ node.cases.push(msg);
1209
+ } while (context.currentType !== 14 /* TokenTypes.EOF */);
1210
+ if (hasEmptyMessage) {
1211
+ emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1212
+ }
1213
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1214
+ return node;
1215
+ }
1216
+ function parseResource(tokenizer) {
1217
+ const context = tokenizer.context();
1218
+ const { offset, startLoc } = context;
1219
+ const msgNode = parseMessage(tokenizer);
1220
+ if (context.currentType === 14 /* TokenTypes.EOF */) {
1221
+ return msgNode;
1222
+ }
1223
+ else {
1224
+ return parsePlural(tokenizer, offset, startLoc, msgNode);
1225
+ }
1226
+ }
1227
+ function parse(source) {
1228
+ const tokenizer = createTokenizer(source, assign({}, options));
1229
+ const context = tokenizer.context();
1230
+ const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1231
+ if (location && node.loc) {
1232
+ node.loc.source = source;
1233
+ }
1234
+ node.body = parseResource(tokenizer);
1235
+ if (options.onCacheKey) {
1236
+ node.cacheKey = options.onCacheKey(source);
1237
+ }
1238
+ // assert whether achieved to EOF
1239
+ if (context.currentType !== 14 /* TokenTypes.EOF */) {
1240
+ emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1241
+ }
1242
+ endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1243
+ return node;
1244
+ }
1245
+ return { parse };
1246
+ }
1247
+ function getTokenCaption(token) {
1248
+ if (token.type === 14 /* TokenTypes.EOF */) {
1249
+ return 'EOF';
1250
+ }
1251
+ const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1252
+ return name.length > 10 ? name.slice(0, 9) + '…' : name;
1253
+ }
1254
+
1255
+ function createTransformer(ast, options = {} // eslint-disable-line
1256
+ ) {
1257
+ const _context = {
1258
+ ast,
1259
+ helpers: new Set()
1260
+ };
1261
+ const context = () => _context;
1262
+ const helper = (name) => {
1263
+ _context.helpers.add(name);
1264
+ return name;
1265
+ };
1266
+ return { context, helper };
1267
+ }
1268
+ function traverseNodes(nodes, transformer) {
1269
+ for (let i = 0; i < nodes.length; i++) {
1270
+ traverseNode(nodes[i], transformer);
1271
+ }
1272
+ }
1273
+ function traverseNode(node, transformer) {
1274
+ // TODO: if we need pre-hook of transform, should be implemented to here
1275
+ switch (node.type) {
1276
+ case 1 /* NodeTypes.Plural */:
1277
+ traverseNodes(node.cases, transformer);
1278
+ transformer.helper("plural" /* HelperNameMap.PLURAL */);
1279
+ break;
1280
+ case 2 /* NodeTypes.Message */:
1281
+ traverseNodes(node.items, transformer);
1282
+ break;
1283
+ case 6 /* NodeTypes.Linked */:
1284
+ const linked = node;
1285
+ traverseNode(linked.key, transformer);
1286
+ transformer.helper("linked" /* HelperNameMap.LINKED */);
1287
+ transformer.helper("type" /* HelperNameMap.TYPE */);
1288
+ break;
1289
+ case 5 /* NodeTypes.List */:
1290
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1291
+ transformer.helper("list" /* HelperNameMap.LIST */);
1292
+ break;
1293
+ case 4 /* NodeTypes.Named */:
1294
+ transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1295
+ transformer.helper("named" /* HelperNameMap.NAMED */);
1296
+ break;
1297
+ }
1298
+ // TODO: if we need post-hook of transform, should be implemented to here
1299
+ }
1300
+ // transform AST
1301
+ function transform(ast, options = {} // eslint-disable-line
1302
+ ) {
1303
+ const transformer = createTransformer(ast);
1304
+ transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1305
+ // traverse
1306
+ ast.body && traverseNode(ast.body, transformer);
1307
+ // set meta information
1308
+ const context = transformer.context();
1309
+ ast.helpers = Array.from(context.helpers);
443
1310
  }
444
1311
 
445
- const DEFAULT_MODIFIER = (str) => str;
446
- const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
447
- const DEFAULT_MESSAGE_DATA_TYPE = 'text';
448
- const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
449
- const DEFAULT_INTERPOLATE = toDisplayString;
450
- function pluralDefault(choice, choicesLength) {
451
- choice = Math.abs(choice);
452
- if (choicesLength === 2) {
453
- // prettier-ignore
454
- return choice
455
- ? choice > 1
456
- ? 1
457
- : 0
458
- : 1;
459
- }
460
- return choice ? Math.min(choice, 2) : 0;
461
- }
462
- function getPluralIndex(options) {
463
- // prettier-ignore
464
- const index = isNumber(options.pluralIndex)
465
- ? options.pluralIndex
466
- : -1;
467
- // prettier-ignore
468
- return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
469
- ? isNumber(options.named.count)
470
- ? options.named.count
471
- : isNumber(options.named.n)
472
- ? options.named.n
473
- : index
474
- : index;
475
- }
476
- function normalizeNamed(pluralIndex, props) {
477
- if (!props.count) {
478
- props.count = pluralIndex;
479
- }
480
- if (!props.n) {
481
- props.n = pluralIndex;
482
- }
483
- }
484
- function createMessageContext(options = {}) {
485
- const locale = options.locale;
486
- const pluralIndex = getPluralIndex(options);
487
- const pluralRule = isObject(options.pluralRules) &&
488
- isString(locale) &&
489
- isFunction(options.pluralRules[locale])
490
- ? options.pluralRules[locale]
491
- : pluralDefault;
492
- const orgPluralRule = isObject(options.pluralRules) &&
493
- isString(locale) &&
494
- isFunction(options.pluralRules[locale])
495
- ? pluralDefault
496
- : undefined;
497
- const plural = (messages) => {
498
- return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
499
- };
500
- const _list = options.list || [];
501
- const list = (index) => _list[index];
502
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
503
- const _named = options.named || {};
504
- isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
505
- const named = (key) => _named[key];
506
- function message(key) {
507
- // prettier-ignore
508
- const msg = isFunction(options.messages)
509
- ? options.messages(key)
510
- : isObject(options.messages)
511
- ? options.messages[key]
512
- : false;
513
- return !msg
514
- ? options.parent
515
- ? options.parent.message(key) // resolve from parent messages
516
- : DEFAULT_MESSAGE
517
- : msg;
518
- }
519
- const _modifier = (name) => options.modifiers
520
- ? options.modifiers[name]
521
- : DEFAULT_MODIFIER;
522
- const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
523
- ? options.processor.normalize
524
- : DEFAULT_NORMALIZE;
525
- const interpolate = isPlainObject(options.processor) &&
526
- isFunction(options.processor.interpolate)
527
- ? options.processor.interpolate
528
- : DEFAULT_INTERPOLATE;
529
- const type = isPlainObject(options.processor) && isString(options.processor.type)
530
- ? options.processor.type
531
- : DEFAULT_MESSAGE_DATA_TYPE;
532
- const linked = (key, ...args) => {
533
- const [arg1, arg2] = args;
534
- let type = 'text';
535
- let modifier = '';
536
- if (args.length === 1) {
537
- if (isObject(arg1)) {
538
- modifier = arg1.modifier || modifier;
539
- type = arg1.type || type;
540
- }
541
- else if (isString(arg1)) {
542
- modifier = arg1 || modifier;
543
- }
544
- }
545
- else if (args.length === 2) {
546
- if (isString(arg1)) {
547
- modifier = arg1 || modifier;
548
- }
549
- if (isString(arg2)) {
550
- type = arg2 || type;
551
- }
552
- }
553
- let msg = message(key)(ctx);
554
- // The message in vnode resolved with linked are returned as an array by processor.nomalize
555
- if (type === 'vnode' && isArray(msg) && modifier) {
556
- msg = msg[0];
557
- }
558
- return modifier ? _modifier(modifier)(msg, type) : msg;
559
- };
560
- const ctx = {
561
- ["list" /* LIST */]: list,
562
- ["named" /* NAMED */]: named,
563
- ["plural" /* PLURAL */]: plural,
564
- ["linked" /* LINKED */]: linked,
565
- ["message" /* MESSAGE */]: message,
566
- ["type" /* TYPE */]: type,
567
- ["interpolate" /* INTERPOLATE */]: interpolate,
568
- ["normalize" /* NORMALIZE */]: normalize
569
- };
570
- return ctx;
1312
+ function optimize(ast) {
1313
+ const body = ast.body;
1314
+ if (body.type === 2 /* NodeTypes.Message */) {
1315
+ optimizeMessageNode(body);
1316
+ }
1317
+ else {
1318
+ body.cases.forEach(c => optimizeMessageNode(c));
1319
+ }
1320
+ return ast;
1321
+ }
1322
+ function optimizeMessageNode(message) {
1323
+ if (message.items.length === 1) {
1324
+ const item = message.items[0];
1325
+ if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1326
+ message.static = item.value;
1327
+ }
1328
+ }
1329
+ else {
1330
+ const values = [];
1331
+ for (let i = 0; i < message.items.length; i++) {
1332
+ const item = message.items[i];
1333
+ if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1334
+ break;
1335
+ }
1336
+ values.push(item.value);
1337
+ }
1338
+ if (values.length === message.items.length) {
1339
+ message.static = join(values);
1340
+ }
1341
+ }
571
1342
  }
572
1343
 
573
- const IntlifyDevToolsHooks = {
574
- I18nInit: 'i18n:init',
575
- FunctionTranslate: 'function:translate'
1344
+ function createCodeGenerator(ast, options) {
1345
+ const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1346
+ const location = options.location !== false;
1347
+ const _context = {
1348
+ filename,
1349
+ code: '',
1350
+ column: 1,
1351
+ line: 1,
1352
+ offset: 0,
1353
+ map: undefined,
1354
+ breakLineCode,
1355
+ needIndent: _needIndent,
1356
+ indentLevel: 0
1357
+ };
1358
+ if (location && ast.loc) {
1359
+ _context.source = ast.loc.source;
1360
+ }
1361
+ const context = () => _context;
1362
+ function push(code, node) {
1363
+ _context.code += code;
1364
+ }
1365
+ function _newline(n, withBreakLine = true) {
1366
+ const _breakLineCode = withBreakLine ? breakLineCode : '';
1367
+ push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1368
+ }
1369
+ function indent(withNewLine = true) {
1370
+ const level = ++_context.indentLevel;
1371
+ withNewLine && _newline(level);
1372
+ }
1373
+ function deindent(withNewLine = true) {
1374
+ const level = --_context.indentLevel;
1375
+ withNewLine && _newline(level);
1376
+ }
1377
+ function newline() {
1378
+ _newline(_context.indentLevel);
1379
+ }
1380
+ const helper = (key) => `_${key}`;
1381
+ const needIndent = () => _context.needIndent;
1382
+ return {
1383
+ context,
1384
+ push,
1385
+ indent,
1386
+ deindent,
1387
+ newline,
1388
+ helper,
1389
+ needIndent
1390
+ };
1391
+ }
1392
+ function generateLinkedNode(generator, node) {
1393
+ const { helper } = generator;
1394
+ generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1395
+ generateNode(generator, node.key);
1396
+ if (node.modifier) {
1397
+ generator.push(`, `);
1398
+ generateNode(generator, node.modifier);
1399
+ generator.push(`, _type`);
1400
+ }
1401
+ else {
1402
+ generator.push(`, undefined, _type`);
1403
+ }
1404
+ generator.push(`)`);
1405
+ }
1406
+ function generateMessageNode(generator, node) {
1407
+ const { helper, needIndent } = generator;
1408
+ generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1409
+ generator.indent(needIndent());
1410
+ const length = node.items.length;
1411
+ for (let i = 0; i < length; i++) {
1412
+ generateNode(generator, node.items[i]);
1413
+ if (i === length - 1) {
1414
+ break;
1415
+ }
1416
+ generator.push(', ');
1417
+ }
1418
+ generator.deindent(needIndent());
1419
+ generator.push('])');
1420
+ }
1421
+ function generatePluralNode(generator, node) {
1422
+ const { helper, needIndent } = generator;
1423
+ if (node.cases.length > 1) {
1424
+ generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1425
+ generator.indent(needIndent());
1426
+ const length = node.cases.length;
1427
+ for (let i = 0; i < length; i++) {
1428
+ generateNode(generator, node.cases[i]);
1429
+ if (i === length - 1) {
1430
+ break;
1431
+ }
1432
+ generator.push(', ');
1433
+ }
1434
+ generator.deindent(needIndent());
1435
+ generator.push(`])`);
1436
+ }
1437
+ }
1438
+ function generateResource(generator, node) {
1439
+ if (node.body) {
1440
+ generateNode(generator, node.body);
1441
+ }
1442
+ else {
1443
+ generator.push('null');
1444
+ }
1445
+ }
1446
+ function generateNode(generator, node) {
1447
+ const { helper } = generator;
1448
+ switch (node.type) {
1449
+ case 0 /* NodeTypes.Resource */:
1450
+ generateResource(generator, node);
1451
+ break;
1452
+ case 1 /* NodeTypes.Plural */:
1453
+ generatePluralNode(generator, node);
1454
+ break;
1455
+ case 2 /* NodeTypes.Message */:
1456
+ generateMessageNode(generator, node);
1457
+ break;
1458
+ case 6 /* NodeTypes.Linked */:
1459
+ generateLinkedNode(generator, node);
1460
+ break;
1461
+ case 8 /* NodeTypes.LinkedModifier */:
1462
+ generator.push(JSON.stringify(node.value), node);
1463
+ break;
1464
+ case 7 /* NodeTypes.LinkedKey */:
1465
+ generator.push(JSON.stringify(node.value), node);
1466
+ break;
1467
+ case 5 /* NodeTypes.List */:
1468
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1469
+ break;
1470
+ case 4 /* NodeTypes.Named */:
1471
+ generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1472
+ break;
1473
+ case 9 /* NodeTypes.Literal */:
1474
+ generator.push(JSON.stringify(node.value), node);
1475
+ break;
1476
+ case 3 /* NodeTypes.Text */:
1477
+ generator.push(JSON.stringify(node.value), node);
1478
+ break;
1479
+ default:
1480
+ {
1481
+ throw new Error(`unhandled codegen node type: ${node.type}`);
1482
+ }
1483
+ }
1484
+ }
1485
+ // generate code from AST
1486
+ const generate = (ast, options = {} // eslint-disable-line
1487
+ ) => {
1488
+ const mode = isString(options.mode) ? options.mode : 'normal';
1489
+ const filename = isString(options.filename)
1490
+ ? options.filename
1491
+ : 'message.intl';
1492
+ const sourceMap = !!options.sourceMap;
1493
+ // prettier-ignore
1494
+ const breakLineCode = options.breakLineCode != null
1495
+ ? options.breakLineCode
1496
+ : mode === 'arrow'
1497
+ ? ';'
1498
+ : '\n';
1499
+ const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1500
+ const helpers = ast.helpers || [];
1501
+ const generator = createCodeGenerator(ast, {
1502
+ mode,
1503
+ filename,
1504
+ sourceMap,
1505
+ breakLineCode,
1506
+ needIndent
1507
+ });
1508
+ generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1509
+ generator.indent(needIndent);
1510
+ if (helpers.length > 0) {
1511
+ generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1512
+ generator.newline();
1513
+ }
1514
+ generator.push(`return `);
1515
+ generateNode(generator, ast);
1516
+ generator.deindent(needIndent);
1517
+ generator.push(`}`);
1518
+ delete ast.helpers;
1519
+ const { code, map } = generator.context();
1520
+ return {
1521
+ ast,
1522
+ code,
1523
+ map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1524
+ };
576
1525
  };
577
1526
 
578
- let devtools = null;
579
- function setDevToolsHook(hook) {
580
- devtools = hook;
581
- }
582
- function getDevToolsHook() {
583
- return devtools;
584
- }
585
- function initI18nDevTools(i18n, version, meta) {
586
- // TODO: queue if devtools is undefined
587
- devtools &&
588
- devtools.emit(IntlifyDevToolsHooks.I18nInit, {
589
- timestamp: Date.now(),
590
- i18n,
591
- version,
592
- meta
593
- });
594
- }
595
- const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
596
- function createDevToolsHook(hook) {
597
- return (payloads) => devtools && devtools.emit(hook, payloads);
1527
+ function baseCompile$1(source, options = {}) {
1528
+ const assignedOptions = assign({}, options);
1529
+ const jit = !!assignedOptions.jit;
1530
+ const doOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1531
+ // parse source codes
1532
+ const parser = createParser(assignedOptions);
1533
+ const ast = parser.parse(source);
1534
+ if (!jit) {
1535
+ // transform ASTs
1536
+ transform(ast, assignedOptions);
1537
+ // optimize ASTs
1538
+ doOptimize && optimize(ast);
1539
+ // generate javascript codes
1540
+ return generate(ast, assignedOptions);
1541
+ }
1542
+ else {
1543
+ // optimize ASTs
1544
+ doOptimize && optimize(ast);
1545
+ // In JIT mode, no ast transform, no code generation.
1546
+ return { ast, code: '' };
1547
+ }
598
1548
  }
599
1549
 
600
- const CoreWarnCodes = {
601
- NOT_FOUND_KEY: 1,
602
- FALLBACK_TO_TRANSLATE: 2,
603
- CANNOT_FORMAT_NUMBER: 3,
604
- FALLBACK_TO_NUMBER_FORMAT: 4,
605
- CANNOT_FORMAT_DATE: 5,
606
- FALLBACK_TO_DATE_FORMAT: 6,
607
- __EXTEND_POINT__: 7
608
- };
609
- /** @internal */
610
- const warnMessages = {
611
- [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
612
- [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
613
- [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
614
- [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
615
- [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
616
- [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
617
- };
618
- function getWarnMessage(code, ...args) {
619
- return format(warnMessages[code], ...args);
1550
+ const pathStateMachine = [];
1551
+ pathStateMachine[0 /* States.BEFORE_PATH */] = {
1552
+ ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
1553
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1554
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1555
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1556
+ };
1557
+ pathStateMachine[1 /* States.IN_PATH */] = {
1558
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
1559
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
1560
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
1561
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
1562
+ };
1563
+ pathStateMachine[2 /* States.BEFORE_IDENT */] = {
1564
+ ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
1565
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1566
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
1567
+ };
1568
+ pathStateMachine[3 /* States.IN_IDENT */] = {
1569
+ ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1570
+ ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
1571
+ ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
1572
+ ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
1573
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
1574
+ ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
1575
+ };
1576
+ pathStateMachine[4 /* States.IN_SUB_PATH */] = {
1577
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
1578
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
1579
+ ["[" /* PathCharTypes.LEFT_BRACKET */]: [
1580
+ 4 /* States.IN_SUB_PATH */,
1581
+ 2 /* Actions.INC_SUB_PATH_DEPTH */
1582
+ ],
1583
+ ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
1584
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1585
+ ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
1586
+ };
1587
+ pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
1588
+ ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1589
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1590
+ ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
1591
+ };
1592
+ pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
1593
+ ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
1594
+ ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
1595
+ ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
1596
+ };
1597
+ /**
1598
+ * Check if an expression is a literal value.
1599
+ */
1600
+ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
1601
+ function isLiteral(exp) {
1602
+ return literalValueRE.test(exp);
1603
+ }
1604
+ /**
1605
+ * Strip quotes from a string
1606
+ */
1607
+ function stripQuotes(str) {
1608
+ const a = str.charCodeAt(0);
1609
+ const b = str.charCodeAt(str.length - 1);
1610
+ return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
1611
+ }
1612
+ /**
1613
+ * Determine the type of a character in a keypath.
1614
+ */
1615
+ function getPathCharType(ch) {
1616
+ if (ch === undefined || ch === null) {
1617
+ return "o" /* PathCharTypes.END_OF_FAIL */;
1618
+ }
1619
+ const code = ch.charCodeAt(0);
1620
+ switch (code) {
1621
+ case 0x5b: // [
1622
+ case 0x5d: // ]
1623
+ case 0x2e: // .
1624
+ case 0x22: // "
1625
+ case 0x27: // '
1626
+ return ch;
1627
+ case 0x5f: // _
1628
+ case 0x24: // $
1629
+ case 0x2d: // -
1630
+ return "i" /* PathCharTypes.IDENT */;
1631
+ case 0x09: // Tab (HT)
1632
+ case 0x0a: // Newline (LF)
1633
+ case 0x0d: // Return (CR)
1634
+ case 0xa0: // No-break space (NBSP)
1635
+ case 0xfeff: // Byte Order Mark (BOM)
1636
+ case 0x2028: // Line Separator (LS)
1637
+ case 0x2029: // Paragraph Separator (PS)
1638
+ return "w" /* PathCharTypes.WORKSPACE */;
1639
+ }
1640
+ return "i" /* PathCharTypes.IDENT */;
1641
+ }
1642
+ /**
1643
+ * Format a subPath, return its plain form if it is
1644
+ * a literal string or number. Otherwise prepend the
1645
+ * dynamic indicator (*).
1646
+ */
1647
+ function formatSubPath(path) {
1648
+ const trimmed = path.trim();
1649
+ // invalid leading 0
1650
+ if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
1651
+ return false;
1652
+ }
1653
+ return isLiteral(trimmed)
1654
+ ? stripQuotes(trimmed)
1655
+ : "*" /* PathCharTypes.ASTARISK */ + trimmed;
1656
+ }
1657
+ /**
1658
+ * Parse a string path into an array of segments
1659
+ */
1660
+ function parse(path) {
1661
+ const keys = [];
1662
+ let index = -1;
1663
+ let mode = 0 /* States.BEFORE_PATH */;
1664
+ let subPathDepth = 0;
1665
+ let c;
1666
+ let key; // eslint-disable-line
1667
+ let newChar;
1668
+ let type;
1669
+ let transition;
1670
+ let action;
1671
+ let typeMap;
1672
+ const actions = [];
1673
+ actions[0 /* Actions.APPEND */] = () => {
1674
+ if (key === undefined) {
1675
+ key = newChar;
1676
+ }
1677
+ else {
1678
+ key += newChar;
1679
+ }
1680
+ };
1681
+ actions[1 /* Actions.PUSH */] = () => {
1682
+ if (key !== undefined) {
1683
+ keys.push(key);
1684
+ key = undefined;
1685
+ }
1686
+ };
1687
+ actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
1688
+ actions[0 /* Actions.APPEND */]();
1689
+ subPathDepth++;
1690
+ };
1691
+ actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
1692
+ if (subPathDepth > 0) {
1693
+ subPathDepth--;
1694
+ mode = 4 /* States.IN_SUB_PATH */;
1695
+ actions[0 /* Actions.APPEND */]();
1696
+ }
1697
+ else {
1698
+ subPathDepth = 0;
1699
+ if (key === undefined) {
1700
+ return false;
1701
+ }
1702
+ key = formatSubPath(key);
1703
+ if (key === false) {
1704
+ return false;
1705
+ }
1706
+ else {
1707
+ actions[1 /* Actions.PUSH */]();
1708
+ }
1709
+ }
1710
+ };
1711
+ function maybeUnescapeQuote() {
1712
+ const nextChar = path[index + 1];
1713
+ if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
1714
+ nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
1715
+ (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
1716
+ nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
1717
+ index++;
1718
+ newChar = '\\' + nextChar;
1719
+ actions[0 /* Actions.APPEND */]();
1720
+ return true;
1721
+ }
1722
+ }
1723
+ while (mode !== null) {
1724
+ index++;
1725
+ c = path[index];
1726
+ if (c === '\\' && maybeUnescapeQuote()) {
1727
+ continue;
1728
+ }
1729
+ type = getPathCharType(c);
1730
+ typeMap = pathStateMachine[mode];
1731
+ transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
1732
+ // check parse error
1733
+ if (transition === 8 /* States.ERROR */) {
1734
+ return;
1735
+ }
1736
+ mode = transition[0];
1737
+ if (transition[1] !== undefined) {
1738
+ action = actions[transition[1]];
1739
+ if (action) {
1740
+ newChar = c;
1741
+ if (action() === false) {
1742
+ return;
1743
+ }
1744
+ }
1745
+ }
1746
+ // check parse finish
1747
+ if (mode === 7 /* States.AFTER_PATH */) {
1748
+ return keys;
1749
+ }
1750
+ }
1751
+ }
1752
+ // path token cache
1753
+ const cache = new Map();
1754
+ /**
1755
+ * key-value message resolver
1756
+ *
1757
+ * @remarks
1758
+ * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
1759
+ *
1760
+ * @param obj - A target object to be resolved with path
1761
+ * @param path - A {@link Path | path} to resolve the value of message
1762
+ *
1763
+ * @returns A resolved {@link PathValue | path value}
1764
+ *
1765
+ * @VueI18nGeneral
1766
+ */
1767
+ function resolveWithKeyValue(obj, path) {
1768
+ return isObject(obj) ? obj[path] : null;
1769
+ }
1770
+ /**
1771
+ * message resolver
1772
+ *
1773
+ * @remarks
1774
+ * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
1775
+ *
1776
+ * @param obj - A target object to be resolved with path
1777
+ * @param path - A {@link Path | path} to resolve the value of message
1778
+ *
1779
+ * @returns A resolved {@link PathValue | path value}
1780
+ *
1781
+ * @VueI18nGeneral
1782
+ */
1783
+ function resolveValue(obj, path) {
1784
+ // check object
1785
+ if (!isObject(obj)) {
1786
+ return null;
1787
+ }
1788
+ // parse path
1789
+ let hit = cache.get(path);
1790
+ if (!hit) {
1791
+ hit = parse(path);
1792
+ if (hit) {
1793
+ cache.set(path, hit);
1794
+ }
1795
+ }
1796
+ // check hit
1797
+ if (!hit) {
1798
+ return null;
1799
+ }
1800
+ // resolve path value
1801
+ const len = hit.length;
1802
+ let last = obj;
1803
+ let i = 0;
1804
+ while (i < len) {
1805
+ const val = last[hit[i]];
1806
+ if (val === undefined) {
1807
+ return null;
1808
+ }
1809
+ last = val;
1810
+ i++;
1811
+ }
1812
+ return last;
620
1813
  }
621
1814
 
622
- /**
623
- * Fallback with simple implemenation
624
- *
625
- * @remarks
626
- * A fallback locale function implemented with a simple fallback algorithm.
627
- *
628
- * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
629
- *
630
- * @param ctx - A {@link CoreContext | context}
631
- * @param fallback - A {@link FallbackLocale | fallback locale}
632
- * @param start - A starting {@link Locale | locale}
633
- *
634
- * @returns Fallback locales
635
- *
636
- * @VueI18nGeneral
637
- */
638
- function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
639
- ) {
640
- // prettier-ignore
641
- return [...new Set([
642
- start,
643
- ...(isArray(fallback)
644
- ? fallback
645
- : isObject(fallback)
646
- ? Object.keys(fallback)
647
- : isString(fallback)
648
- ? [fallback]
649
- : [start])
650
- ])];
651
- }
652
- /**
653
- * Fallback with locale chain
654
- *
655
- * @remarks
656
- * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
657
- *
658
- * @param ctx - A {@link CoreContext | context}
659
- * @param fallback - A {@link FallbackLocale | fallback locale}
660
- * @param start - A starting {@link Locale | locale}
661
- *
662
- * @returns Fallback locales
663
- *
664
- * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
665
- *
666
- * @VueI18nGeneral
667
- */
668
- function fallbackWithLocaleChain(ctx, fallback, start) {
669
- const startLocale = isString(start) ? start : DEFAULT_LOCALE;
670
- const context = ctx;
671
- if (!context.__localeChainCache) {
672
- context.__localeChainCache = new Map();
673
- }
674
- let chain = context.__localeChainCache.get(startLocale);
675
- if (!chain) {
676
- chain = [];
677
- // first block defined by start
678
- let block = [start];
679
- // while any intervening block found
680
- while (isArray(block)) {
681
- block = appendBlockToChain(chain, block, fallback);
682
- }
683
- // prettier-ignore
684
- // last block defined by default
685
- const defaults = isArray(fallback) || !isPlainObject(fallback)
686
- ? fallback
687
- : fallback['default']
688
- ? fallback['default']
689
- : null;
690
- // convert defaults to array
691
- block = isString(defaults) ? [defaults] : defaults;
692
- if (isArray(block)) {
693
- appendBlockToChain(chain, block, false);
694
- }
695
- context.__localeChainCache.set(startLocale, chain);
696
- }
697
- return chain;
698
- }
699
- function appendBlockToChain(chain, block, blocks) {
700
- let follow = true;
701
- for (let i = 0; i < block.length && isBoolean(follow); i++) {
702
- const locale = block[i];
703
- if (isString(locale)) {
704
- follow = appendLocaleToChain(chain, block[i], blocks);
705
- }
706
- }
707
- return follow;
708
- }
709
- function appendLocaleToChain(chain, locale, blocks) {
710
- let follow;
711
- const tokens = locale.split('-');
712
- do {
713
- const target = tokens.join('-');
714
- follow = appendItemToChain(chain, target, blocks);
715
- tokens.splice(-1, 1);
716
- } while (tokens.length && follow === true);
717
- return follow;
718
- }
719
- function appendItemToChain(chain, target, blocks) {
720
- let follow = false;
721
- if (!chain.includes(target)) {
722
- follow = true;
723
- if (target) {
724
- follow = target[target.length - 1] !== '!';
725
- const locale = target.replace(/!/g, '');
726
- chain.push(locale);
727
- if ((isArray(blocks) || isPlainObject(blocks)) &&
728
- blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
729
- ) {
730
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
731
- follow = blocks[locale];
732
- }
733
- }
734
- }
735
- return follow;
1815
+ const DEFAULT_MODIFIER = (str) => str;
1816
+ const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
1817
+ const DEFAULT_MESSAGE_DATA_TYPE = 'text';
1818
+ const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
1819
+ const DEFAULT_INTERPOLATE = toDisplayString;
1820
+ function pluralDefault(choice, choicesLength) {
1821
+ choice = Math.abs(choice);
1822
+ if (choicesLength === 2) {
1823
+ // prettier-ignore
1824
+ return choice
1825
+ ? choice > 1
1826
+ ? 1
1827
+ : 0
1828
+ : 1;
1829
+ }
1830
+ return choice ? Math.min(choice, 2) : 0;
1831
+ }
1832
+ function getPluralIndex(options) {
1833
+ // prettier-ignore
1834
+ const index = isNumber(options.pluralIndex)
1835
+ ? options.pluralIndex
1836
+ : -1;
1837
+ // prettier-ignore
1838
+ return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
1839
+ ? isNumber(options.named.count)
1840
+ ? options.named.count
1841
+ : isNumber(options.named.n)
1842
+ ? options.named.n
1843
+ : index
1844
+ : index;
1845
+ }
1846
+ function normalizeNamed(pluralIndex, props) {
1847
+ if (!props.count) {
1848
+ props.count = pluralIndex;
1849
+ }
1850
+ if (!props.n) {
1851
+ props.n = pluralIndex;
1852
+ }
736
1853
  }
1854
+ function createMessageContext(options = {}) {
1855
+ const locale = options.locale;
1856
+ const pluralIndex = getPluralIndex(options);
1857
+ const pluralRule = isObject(options.pluralRules) &&
1858
+ isString(locale) &&
1859
+ isFunction(options.pluralRules[locale])
1860
+ ? options.pluralRules[locale]
1861
+ : pluralDefault;
1862
+ const orgPluralRule = isObject(options.pluralRules) &&
1863
+ isString(locale) &&
1864
+ isFunction(options.pluralRules[locale])
1865
+ ? pluralDefault
1866
+ : undefined;
1867
+ const plural = (messages) => {
1868
+ return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
1869
+ };
1870
+ const _list = options.list || [];
1871
+ const list = (index) => _list[index];
1872
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1873
+ const _named = options.named || {};
1874
+ isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
1875
+ const named = (key) => _named[key];
1876
+ function message(key) {
1877
+ // prettier-ignore
1878
+ const msg = isFunction(options.messages)
1879
+ ? options.messages(key)
1880
+ : isObject(options.messages)
1881
+ ? options.messages[key]
1882
+ : false;
1883
+ return !msg
1884
+ ? options.parent
1885
+ ? options.parent.message(key) // resolve from parent messages
1886
+ : DEFAULT_MESSAGE
1887
+ : msg;
1888
+ }
1889
+ const _modifier = (name) => options.modifiers
1890
+ ? options.modifiers[name]
1891
+ : DEFAULT_MODIFIER;
1892
+ const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
1893
+ ? options.processor.normalize
1894
+ : DEFAULT_NORMALIZE;
1895
+ const interpolate = isPlainObject(options.processor) &&
1896
+ isFunction(options.processor.interpolate)
1897
+ ? options.processor.interpolate
1898
+ : DEFAULT_INTERPOLATE;
1899
+ const type = isPlainObject(options.processor) && isString(options.processor.type)
1900
+ ? options.processor.type
1901
+ : DEFAULT_MESSAGE_DATA_TYPE;
1902
+ const linked = (key, ...args) => {
1903
+ const [arg1, arg2] = args;
1904
+ let type = 'text';
1905
+ let modifier = '';
1906
+ if (args.length === 1) {
1907
+ if (isObject(arg1)) {
1908
+ modifier = arg1.modifier || modifier;
1909
+ type = arg1.type || type;
1910
+ }
1911
+ else if (isString(arg1)) {
1912
+ modifier = arg1 || modifier;
1913
+ }
1914
+ }
1915
+ else if (args.length === 2) {
1916
+ if (isString(arg1)) {
1917
+ modifier = arg1 || modifier;
1918
+ }
1919
+ if (isString(arg2)) {
1920
+ type = arg2 || type;
1921
+ }
1922
+ }
1923
+ const ret = message(key)(ctx);
1924
+ const msg =
1925
+ // The message in vnode resolved with linked are returned as an array by processor.nomalize
1926
+ type === 'vnode' && isArray(ret) && modifier
1927
+ ? ret[0]
1928
+ : ret;
1929
+ return modifier ? _modifier(modifier)(msg, type) : msg;
1930
+ };
1931
+ const ctx = {
1932
+ ["list" /* HelperNameMap.LIST */]: list,
1933
+ ["named" /* HelperNameMap.NAMED */]: named,
1934
+ ["plural" /* HelperNameMap.PLURAL */]: plural,
1935
+ ["linked" /* HelperNameMap.LINKED */]: linked,
1936
+ ["message" /* HelperNameMap.MESSAGE */]: message,
1937
+ ["type" /* HelperNameMap.TYPE */]: type,
1938
+ ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
1939
+ ["normalize" /* HelperNameMap.NORMALIZE */]: normalize
1940
+ };
1941
+ return ctx;
1942
+ }
1943
+
1944
+ const IntlifyDevToolsHooks = {
1945
+ I18nInit: 'i18n:init',
1946
+ FunctionTranslate: 'function:translate'
1947
+ };
737
1948
 
738
- /* eslint-disable @typescript-eslint/no-explicit-any */
739
- /**
740
- * Intlify core-base version
741
- * @internal
742
- */
743
- const VERSION = '9.3.0-beta.2';
744
- const NOT_REOSLVED = -1;
745
- const DEFAULT_LOCALE = 'en-US';
746
- const MISSING_RESOLVE_VALUE = '';
747
- const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
748
- function getDefaultLinkedModifiers() {
749
- return {
750
- upper: (val, type) => {
751
- // prettier-ignore
752
- return type === 'text' && isString(val)
753
- ? val.toUpperCase()
754
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
755
- ? val.children.toUpperCase()
756
- : val;
757
- },
758
- lower: (val, type) => {
759
- // prettier-ignore
760
- return type === 'text' && isString(val)
761
- ? val.toLowerCase()
762
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
763
- ? val.children.toLowerCase()
764
- : val;
765
- },
766
- capitalize: (val, type) => {
767
- // prettier-ignore
768
- return (type === 'text' && isString(val)
769
- ? capitalize(val)
770
- : type === 'vnode' && isObject(val) && '__v_isVNode' in val
771
- ? capitalize(val.children)
772
- : val);
773
- }
774
- };
775
- }
776
- let _compiler;
777
- function registerMessageCompiler(compiler) {
778
- _compiler = compiler;
779
- }
780
- let _resolver;
781
- /**
782
- * Register the message resolver
783
- *
784
- * @param resolver - A {@link MessageResolver} function
785
- *
786
- * @VueI18nGeneral
787
- */
788
- function registerMessageResolver(resolver) {
789
- _resolver = resolver;
790
- }
791
- let _fallbacker;
792
- /**
793
- * Register the locale fallbacker
794
- *
795
- * @param fallbacker - A {@link LocaleFallbacker} function
796
- *
797
- * @VueI18nGeneral
798
- */
799
- function registerLocaleFallbacker(fallbacker) {
800
- _fallbacker = fallbacker;
801
- }
802
- // Additional Meta for Intlify DevTools
803
- let _additionalMeta = null;
804
- const setAdditionalMeta = (meta) => {
805
- _additionalMeta = meta;
806
- };
807
- const getAdditionalMeta = () => _additionalMeta;
808
- let _fallbackContext = null;
809
- const setFallbackContext = (context) => {
810
- _fallbackContext = context;
811
- };
812
- const getFallbackContext = () => _fallbackContext;
813
- // ID for CoreContext
814
- let _cid = 0;
815
- function createCoreContext(options = {}) {
816
- // setup options
817
- const version = isString(options.version) ? options.version : VERSION;
818
- const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
819
- const fallbackLocale = isArray(options.fallbackLocale) ||
820
- isPlainObject(options.fallbackLocale) ||
821
- isString(options.fallbackLocale) ||
822
- options.fallbackLocale === false
823
- ? options.fallbackLocale
824
- : locale;
825
- const messages = isPlainObject(options.messages)
826
- ? options.messages
827
- : { [locale]: {} };
828
- const datetimeFormats = isPlainObject(options.datetimeFormats)
829
- ? options.datetimeFormats
830
- : { [locale]: {} }
831
- ;
832
- const numberFormats = isPlainObject(options.numberFormats)
833
- ? options.numberFormats
834
- : { [locale]: {} }
835
- ;
836
- const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
837
- const pluralRules = options.pluralRules || {};
838
- const missing = isFunction(options.missing) ? options.missing : null;
839
- const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
840
- ? options.missingWarn
841
- : true;
842
- const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
843
- ? options.fallbackWarn
844
- : true;
845
- const fallbackFormat = !!options.fallbackFormat;
846
- const unresolving = !!options.unresolving;
847
- const postTranslation = isFunction(options.postTranslation)
848
- ? options.postTranslation
849
- : null;
850
- const processor = isPlainObject(options.processor) ? options.processor : null;
851
- const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
852
- ? options.warnHtmlMessage
853
- : true;
854
- const escapeParameter = !!options.escapeParameter;
855
- const messageCompiler = isFunction(options.messageCompiler)
856
- ? options.messageCompiler
857
- : _compiler;
858
- const messageResolver = isFunction(options.messageResolver)
859
- ? options.messageResolver
860
- : _resolver || resolveWithKeyValue;
861
- const localeFallbacker = isFunction(options.localeFallbacker)
862
- ? options.localeFallbacker
863
- : _fallbacker || fallbackWithSimple;
864
- const fallbackContext = isObject(options.fallbackContext)
865
- ? options.fallbackContext
866
- : undefined;
867
- const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
868
- // setup internal options
869
- const internalOptions = options;
870
- const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
871
- ? internalOptions.__datetimeFormatters
872
- : new Map()
873
- ;
874
- const __numberFormatters = isObject(internalOptions.__numberFormatters)
875
- ? internalOptions.__numberFormatters
876
- : new Map()
877
- ;
878
- const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
879
- _cid++;
880
- const context = {
881
- version,
882
- cid: _cid,
883
- locale,
884
- fallbackLocale,
885
- messages,
886
- modifiers,
887
- pluralRules,
888
- missing,
889
- missingWarn,
890
- fallbackWarn,
891
- fallbackFormat,
892
- unresolving,
893
- postTranslation,
894
- processor,
895
- warnHtmlMessage,
896
- escapeParameter,
897
- messageCompiler,
898
- messageResolver,
899
- localeFallbacker,
900
- fallbackContext,
901
- onWarn,
902
- __meta
903
- };
904
- {
905
- context.datetimeFormats = datetimeFormats;
906
- context.numberFormats = numberFormats;
907
- context.__datetimeFormatters = __datetimeFormatters;
908
- context.__numberFormatters = __numberFormatters;
909
- }
910
- // for vue-devtools timeline event
911
- {
912
- context.__v_emitter =
913
- internalOptions.__v_emitter != null
914
- ? internalOptions.__v_emitter
915
- : undefined;
916
- }
917
- // NOTE: experimental !!
918
- {
919
- initI18nDevTools(context, version, __meta);
920
- }
921
- return context;
922
- }
923
- /** @internal */
924
- function isTranslateFallbackWarn(fallback, key) {
925
- return fallback instanceof RegExp ? fallback.test(key) : fallback;
926
- }
927
- /** @internal */
928
- function isTranslateMissingWarn(missing, key) {
929
- return missing instanceof RegExp ? missing.test(key) : missing;
930
- }
931
- /** @internal */
932
- function handleMissing(context, key, locale, missingWarn, type) {
933
- const { missing, onWarn } = context;
934
- // for vue-devtools timeline event
935
- {
936
- const emitter = context.__v_emitter;
937
- if (emitter) {
938
- emitter.emit("missing" /* MISSING */, {
939
- locale,
940
- key,
941
- type,
942
- groupId: `${type}:${key}`
943
- });
944
- }
945
- }
946
- if (missing !== null) {
947
- const ret = missing(context, locale, key, type);
948
- return isString(ret) ? ret : key;
949
- }
950
- else {
951
- if (isTranslateMissingWarn(missingWarn, key)) {
952
- onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
953
- }
954
- return key;
955
- }
956
- }
957
- /** @internal */
958
- function updateFallbackLocale(ctx, locale, fallback) {
959
- const context = ctx;
960
- context.__localeChainCache = new Map();
961
- ctx.localeFallbacker(ctx, fallback, locale);
962
- }
1949
+ let devtools = null;
1950
+ function setDevToolsHook(hook) {
1951
+ devtools = hook;
1952
+ }
1953
+ function getDevToolsHook() {
1954
+ return devtools;
1955
+ }
1956
+ function initI18nDevTools(i18n, version, meta) {
1957
+ // TODO: queue if devtools is undefined
1958
+ devtools &&
1959
+ devtools.emit(IntlifyDevToolsHooks.I18nInit, {
1960
+ timestamp: Date.now(),
1961
+ i18n,
1962
+ version,
1963
+ meta
1964
+ });
1965
+ }
1966
+ const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
1967
+ function createDevToolsHook(hook) {
1968
+ return (payloads) => devtools && devtools.emit(hook, payloads);
1969
+ }
1970
+
1971
+ const CoreWarnCodes = {
1972
+ NOT_FOUND_KEY: 1,
1973
+ FALLBACK_TO_TRANSLATE: 2,
1974
+ CANNOT_FORMAT_NUMBER: 3,
1975
+ FALLBACK_TO_NUMBER_FORMAT: 4,
1976
+ CANNOT_FORMAT_DATE: 5,
1977
+ FALLBACK_TO_DATE_FORMAT: 6,
1978
+ __EXTEND_POINT__: 7
1979
+ };
1980
+ /** @internal */
1981
+ const warnMessages = {
1982
+ [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
1983
+ [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
1984
+ [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
1985
+ [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
1986
+ [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
1987
+ [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
1988
+ };
1989
+ function getWarnMessage(code, ...args) {
1990
+ return format$1(warnMessages[code], ...args);
1991
+ }
1992
+
1993
+ /**
1994
+ * Fallback with simple implemenation
1995
+ *
1996
+ * @remarks
1997
+ * A fallback locale function implemented with a simple fallback algorithm.
1998
+ *
1999
+ * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
2000
+ *
2001
+ * @param ctx - A {@link CoreContext | context}
2002
+ * @param fallback - A {@link FallbackLocale | fallback locale}
2003
+ * @param start - A starting {@link Locale | locale}
2004
+ *
2005
+ * @returns Fallback locales
2006
+ *
2007
+ * @VueI18nGeneral
2008
+ */
2009
+ function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
2010
+ ) {
2011
+ // prettier-ignore
2012
+ return [...new Set([
2013
+ start,
2014
+ ...(isArray(fallback)
2015
+ ? fallback
2016
+ : isObject(fallback)
2017
+ ? Object.keys(fallback)
2018
+ : isString(fallback)
2019
+ ? [fallback]
2020
+ : [start])
2021
+ ])];
2022
+ }
2023
+ /**
2024
+ * Fallback with locale chain
2025
+ *
2026
+ * @remarks
2027
+ * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
2028
+ *
2029
+ * @param ctx - A {@link CoreContext | context}
2030
+ * @param fallback - A {@link FallbackLocale | fallback locale}
2031
+ * @param start - A starting {@link Locale | locale}
2032
+ *
2033
+ * @returns Fallback locales
2034
+ *
2035
+ * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
2036
+ *
2037
+ * @VueI18nGeneral
2038
+ */
2039
+ function fallbackWithLocaleChain(ctx, fallback, start) {
2040
+ const startLocale = isString(start) ? start : DEFAULT_LOCALE;
2041
+ const context = ctx;
2042
+ if (!context.__localeChainCache) {
2043
+ context.__localeChainCache = new Map();
2044
+ }
2045
+ let chain = context.__localeChainCache.get(startLocale);
2046
+ if (!chain) {
2047
+ chain = [];
2048
+ // first block defined by start
2049
+ let block = [start];
2050
+ // while any intervening block found
2051
+ while (isArray(block)) {
2052
+ block = appendBlockToChain(chain, block, fallback);
2053
+ }
2054
+ // prettier-ignore
2055
+ // last block defined by default
2056
+ const defaults = isArray(fallback) || !isPlainObject(fallback)
2057
+ ? fallback
2058
+ : fallback['default']
2059
+ ? fallback['default']
2060
+ : null;
2061
+ // convert defaults to array
2062
+ block = isString(defaults) ? [defaults] : defaults;
2063
+ if (isArray(block)) {
2064
+ appendBlockToChain(chain, block, false);
2065
+ }
2066
+ context.__localeChainCache.set(startLocale, chain);
2067
+ }
2068
+ return chain;
2069
+ }
2070
+ function appendBlockToChain(chain, block, blocks) {
2071
+ let follow = true;
2072
+ for (let i = 0; i < block.length && isBoolean(follow); i++) {
2073
+ const locale = block[i];
2074
+ if (isString(locale)) {
2075
+ follow = appendLocaleToChain(chain, block[i], blocks);
2076
+ }
2077
+ }
2078
+ return follow;
2079
+ }
2080
+ function appendLocaleToChain(chain, locale, blocks) {
2081
+ let follow;
2082
+ const tokens = locale.split('-');
2083
+ do {
2084
+ const target = tokens.join('-');
2085
+ follow = appendItemToChain(chain, target, blocks);
2086
+ tokens.splice(-1, 1);
2087
+ } while (tokens.length && follow === true);
2088
+ return follow;
2089
+ }
2090
+ function appendItemToChain(chain, target, blocks) {
2091
+ let follow = false;
2092
+ if (!chain.includes(target)) {
2093
+ follow = true;
2094
+ if (target) {
2095
+ follow = target[target.length - 1] !== '!';
2096
+ const locale = target.replace(/!/g, '');
2097
+ chain.push(locale);
2098
+ if ((isArray(blocks) || isPlainObject(blocks)) &&
2099
+ blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
2100
+ ) {
2101
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2102
+ follow = blocks[locale];
2103
+ }
2104
+ }
2105
+ }
2106
+ return follow;
2107
+ }
2108
+
2109
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2110
+ /**
2111
+ * Intlify core-base version
2112
+ * @internal
2113
+ */
2114
+ const VERSION = '9.3.0-beta.21';
2115
+ const NOT_REOSLVED = -1;
2116
+ const DEFAULT_LOCALE = 'en-US';
2117
+ const MISSING_RESOLVE_VALUE = '';
2118
+ const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
2119
+ function getDefaultLinkedModifiers() {
2120
+ return {
2121
+ upper: (val, type) => {
2122
+ // prettier-ignore
2123
+ return type === 'text' && isString(val)
2124
+ ? val.toUpperCase()
2125
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2126
+ ? val.children.toUpperCase()
2127
+ : val;
2128
+ },
2129
+ lower: (val, type) => {
2130
+ // prettier-ignore
2131
+ return type === 'text' && isString(val)
2132
+ ? val.toLowerCase()
2133
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2134
+ ? val.children.toLowerCase()
2135
+ : val;
2136
+ },
2137
+ capitalize: (val, type) => {
2138
+ // prettier-ignore
2139
+ return (type === 'text' && isString(val)
2140
+ ? capitalize(val)
2141
+ : type === 'vnode' && isObject(val) && '__v_isVNode' in val
2142
+ ? capitalize(val.children)
2143
+ : val);
2144
+ }
2145
+ };
2146
+ }
2147
+ let _compiler;
2148
+ function registerMessageCompiler(compiler) {
2149
+ _compiler = compiler;
2150
+ }
2151
+ let _resolver;
2152
+ /**
2153
+ * Register the message resolver
2154
+ *
2155
+ * @param resolver - A {@link MessageResolver} function
2156
+ *
2157
+ * @VueI18nGeneral
2158
+ */
2159
+ function registerMessageResolver(resolver) {
2160
+ _resolver = resolver;
2161
+ }
2162
+ let _fallbacker;
2163
+ /**
2164
+ * Register the locale fallbacker
2165
+ *
2166
+ * @param fallbacker - A {@link LocaleFallbacker} function
2167
+ *
2168
+ * @VueI18nGeneral
2169
+ */
2170
+ function registerLocaleFallbacker(fallbacker) {
2171
+ _fallbacker = fallbacker;
2172
+ }
2173
+ // Additional Meta for Intlify DevTools
2174
+ let _additionalMeta = null;
2175
+ const setAdditionalMeta = (meta) => {
2176
+ _additionalMeta = meta;
2177
+ };
2178
+ const getAdditionalMeta = () => _additionalMeta;
2179
+ let _fallbackContext = null;
2180
+ const setFallbackContext = (context) => {
2181
+ _fallbackContext = context;
2182
+ };
2183
+ const getFallbackContext = () => _fallbackContext;
2184
+ // ID for CoreContext
2185
+ let _cid = 0;
2186
+ function createCoreContext(options = {}) {
2187
+ // setup options
2188
+ const version = isString(options.version) ? options.version : VERSION;
2189
+ const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
2190
+ const fallbackLocale = isArray(options.fallbackLocale) ||
2191
+ isPlainObject(options.fallbackLocale) ||
2192
+ isString(options.fallbackLocale) ||
2193
+ options.fallbackLocale === false
2194
+ ? options.fallbackLocale
2195
+ : locale;
2196
+ const messages = isPlainObject(options.messages)
2197
+ ? options.messages
2198
+ : { [locale]: {} };
2199
+ const datetimeFormats = isPlainObject(options.datetimeFormats)
2200
+ ? options.datetimeFormats
2201
+ : { [locale]: {} }
2202
+ ;
2203
+ const numberFormats = isPlainObject(options.numberFormats)
2204
+ ? options.numberFormats
2205
+ : { [locale]: {} }
2206
+ ;
2207
+ const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
2208
+ const pluralRules = options.pluralRules || {};
2209
+ const missing = isFunction(options.missing) ? options.missing : null;
2210
+ const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
2211
+ ? options.missingWarn
2212
+ : true;
2213
+ const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
2214
+ ? options.fallbackWarn
2215
+ : true;
2216
+ const fallbackFormat = !!options.fallbackFormat;
2217
+ const unresolving = !!options.unresolving;
2218
+ const postTranslation = isFunction(options.postTranslation)
2219
+ ? options.postTranslation
2220
+ : null;
2221
+ const processor = isPlainObject(options.processor) ? options.processor : null;
2222
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
2223
+ ? options.warnHtmlMessage
2224
+ : true;
2225
+ const escapeParameter = !!options.escapeParameter;
2226
+ const messageCompiler = isFunction(options.messageCompiler)
2227
+ ? options.messageCompiler
2228
+ : _compiler;
2229
+ const messageResolver = isFunction(options.messageResolver)
2230
+ ? options.messageResolver
2231
+ : _resolver || resolveWithKeyValue;
2232
+ const localeFallbacker = isFunction(options.localeFallbacker)
2233
+ ? options.localeFallbacker
2234
+ : _fallbacker || fallbackWithSimple;
2235
+ const fallbackContext = isObject(options.fallbackContext)
2236
+ ? options.fallbackContext
2237
+ : undefined;
2238
+ const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
2239
+ // setup internal options
2240
+ const internalOptions = options;
2241
+ const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
2242
+ ? internalOptions.__datetimeFormatters
2243
+ : new Map()
2244
+ ;
2245
+ const __numberFormatters = isObject(internalOptions.__numberFormatters)
2246
+ ? internalOptions.__numberFormatters
2247
+ : new Map()
2248
+ ;
2249
+ const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
2250
+ _cid++;
2251
+ const context = {
2252
+ version,
2253
+ cid: _cid,
2254
+ locale,
2255
+ fallbackLocale,
2256
+ messages,
2257
+ modifiers,
2258
+ pluralRules,
2259
+ missing,
2260
+ missingWarn,
2261
+ fallbackWarn,
2262
+ fallbackFormat,
2263
+ unresolving,
2264
+ postTranslation,
2265
+ processor,
2266
+ warnHtmlMessage,
2267
+ escapeParameter,
2268
+ messageCompiler,
2269
+ messageResolver,
2270
+ localeFallbacker,
2271
+ fallbackContext,
2272
+ onWarn,
2273
+ __meta
2274
+ };
2275
+ {
2276
+ context.datetimeFormats = datetimeFormats;
2277
+ context.numberFormats = numberFormats;
2278
+ context.__datetimeFormatters = __datetimeFormatters;
2279
+ context.__numberFormatters = __numberFormatters;
2280
+ }
2281
+ // for vue-devtools timeline event
2282
+ {
2283
+ context.__v_emitter =
2284
+ internalOptions.__v_emitter != null
2285
+ ? internalOptions.__v_emitter
2286
+ : undefined;
2287
+ }
2288
+ // NOTE: experimental !!
2289
+ {
2290
+ initI18nDevTools(context, version, __meta);
2291
+ }
2292
+ return context;
2293
+ }
2294
+ /** @internal */
2295
+ function isTranslateFallbackWarn(fallback, key) {
2296
+ return fallback instanceof RegExp ? fallback.test(key) : fallback;
2297
+ }
2298
+ /** @internal */
2299
+ function isTranslateMissingWarn(missing, key) {
2300
+ return missing instanceof RegExp ? missing.test(key) : missing;
2301
+ }
2302
+ /** @internal */
2303
+ function handleMissing(context, key, locale, missingWarn, type) {
2304
+ const { missing, onWarn } = context;
2305
+ // for vue-devtools timeline event
2306
+ {
2307
+ const emitter = context.__v_emitter;
2308
+ if (emitter) {
2309
+ emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
2310
+ locale,
2311
+ key,
2312
+ type,
2313
+ groupId: `${type}:${key}`
2314
+ });
2315
+ }
2316
+ }
2317
+ if (missing !== null) {
2318
+ const ret = missing(context, locale, key, type);
2319
+ return isString(ret) ? ret : key;
2320
+ }
2321
+ else {
2322
+ if (isTranslateMissingWarn(missingWarn, key)) {
2323
+ onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
2324
+ }
2325
+ return key;
2326
+ }
2327
+ }
2328
+ /** @internal */
2329
+ function updateFallbackLocale(ctx, locale, fallback) {
2330
+ const context = ctx;
2331
+ context.__localeChainCache = new Map();
2332
+ ctx.localeFallbacker(ctx, fallback, locale);
2333
+ }
963
2334
  /* eslint-enable @typescript-eslint/no-explicit-any */
964
2335
 
965
- function clearCompileCache() {
966
- }
967
- function compileToFunction(source, options = {}) {
968
- {
969
- warn(`Runtime compilation is not supported in ${'core.runtime.esm-browser.js' }.`);
970
- return (() => source);
971
- }
2336
+ function format(ast) {
2337
+ const msg = (ctx) => formatParts(ctx, ast);
2338
+ // TODO: add meta data for vue-devtools debugging, such as `key`, `source` and `locale`
2339
+ // TODO: optimization for static text message
2340
+ return msg;
2341
+ }
2342
+ function formatParts(ctx, ast) {
2343
+ if (ast.body.type === 1 /* NodeTypes.Plural */) {
2344
+ return ctx.plural(ast.body.cases.reduce((messages, c) => [
2345
+ ...messages,
2346
+ formatMessageParts(ctx, c)
2347
+ ], []));
2348
+ }
2349
+ else {
2350
+ return formatMessageParts(ctx, ast.body);
2351
+ }
2352
+ }
2353
+ function formatMessageParts(ctx, node) {
2354
+ if (node.static) {
2355
+ return ctx.type === 'text'
2356
+ ? node.static
2357
+ : ctx.normalize([node.static]);
2358
+ }
2359
+ else {
2360
+ const messages = node.items.reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
2361
+ return ctx.normalize(messages);
2362
+ }
2363
+ }
2364
+ function formatMessagePart(ctx, node) {
2365
+ switch (node.type) {
2366
+ case 3 /* NodeTypes.Text */:
2367
+ return node.value;
2368
+ case 9 /* NodeTypes.Literal */:
2369
+ return node.value;
2370
+ case 4 /* NodeTypes.Named */:
2371
+ return ctx.interpolate(ctx.named(node.key));
2372
+ case 5 /* NodeTypes.List */:
2373
+ return ctx.interpolate(ctx.list(node.index));
2374
+ case 6 /* NodeTypes.Linked */:
2375
+ return ctx.linked(formatMessagePart(ctx, node.key), node.modifier
2376
+ ? formatMessagePart(ctx, node.modifier)
2377
+ : undefined, ctx.type);
2378
+ case 7 /* NodeTypes.LinkedKey */:
2379
+ return node.value;
2380
+ case 8 /* NodeTypes.LinkedModifier */:
2381
+ return node.value;
2382
+ default:
2383
+ throw new Error(`unhandled node type on format message part: ${node.type}`);
2384
+ }
972
2385
  }
973
2386
 
974
- let code = CompileErrorCodes.__EXTEND_POINT__;
975
- const inc = () => ++code;
976
- const CoreErrorCodes = {
977
- INVALID_ARGUMENT: code,
978
- INVALID_DATE_ARGUMENT: inc(),
979
- INVALID_ISO_DATE_ARGUMENT: inc(),
980
- __EXTEND_POINT__: inc() // 18
981
- };
982
- function createCoreError(code) {
983
- return createCompileError(code, null, { messages: errorMessages } );
984
- }
985
- /** @internal */
986
- const errorMessages = {
987
- [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
988
- [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
989
- 'Make sure your Date represents a valid date.',
990
- [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
2387
+ let code = CompileErrorCodes.__EXTEND_POINT__;
2388
+ const inc = () => ++code;
2389
+ const CoreErrorCodes = {
2390
+ INVALID_ARGUMENT: code,
2391
+ INVALID_DATE_ARGUMENT: inc(),
2392
+ INVALID_ISO_DATE_ARGUMENT: inc(),
2393
+ NOT_SUPPORT_AST: inc(),
2394
+ __EXTEND_POINT__: inc() // 19
2395
+ };
2396
+ function createCoreError(code) {
2397
+ return createCompileError(code, null, { messages: errorMessages } );
2398
+ }
2399
+ /** @internal */
2400
+ const errorMessages = {
2401
+ [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
2402
+ [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
2403
+ 'Make sure your Date represents a valid date.',
2404
+ [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
2405
+ [CoreErrorCodes.NOT_SUPPORT_AST]: 'Not support AST'
991
2406
  };
992
2407
 
993
- const NOOP_MESSAGE_FUNCTION = () => '';
994
- const isMessageFunction = (val) => isFunction(val);
995
- // implementation of `translate` function
996
- function translate(context, ...args) {
997
- const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
998
- const [key, options] = parseTranslateArgs(...args);
999
- const missingWarn = isBoolean(options.missingWarn)
1000
- ? options.missingWarn
1001
- : context.missingWarn;
1002
- const fallbackWarn = isBoolean(options.fallbackWarn)
1003
- ? options.fallbackWarn
1004
- : context.fallbackWarn;
1005
- const escapeParameter = isBoolean(options.escapeParameter)
1006
- ? options.escapeParameter
1007
- : context.escapeParameter;
1008
- const resolvedMessage = !!options.resolvedMessage;
1009
- // prettier-ignore
1010
- const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
1011
- ? !isBoolean(options.default)
1012
- ? options.default
1013
- : (!messageCompiler ? () => key : key)
1014
- : fallbackFormat // default by `fallbackFormat` option
1015
- ? (!messageCompiler ? () => key : key)
1016
- : '';
1017
- const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
1018
- const locale = isString(options.locale) ? options.locale : context.locale;
1019
- // escape params
1020
- escapeParameter && escapeParams(options);
1021
- // resolve message format
1022
- // eslint-disable-next-line prefer-const
1023
- let [formatScope, targetLocale, message] = !resolvedMessage
1024
- ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
1025
- : [
1026
- key,
1027
- locale,
1028
- messages[locale] || {}
1029
- ];
1030
- // NOTE:
1031
- // Fix to work around `ssrTransfrom` bug in Vite.
1032
- // https://github.com/vitejs/vite/issues/4306
1033
- // To get around this, use temporary variables.
1034
- // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
1035
- let format = formatScope;
1036
- // if you use default message, set it as message format!
1037
- let cacheBaseKey = key;
1038
- if (!resolvedMessage &&
1039
- !(isString(format) || isMessageFunction(format))) {
1040
- if (enableDefaultMsg) {
1041
- format = defaultMsgOrKey;
1042
- cacheBaseKey = format;
1043
- }
1044
- }
1045
- // checking message format and target locale
1046
- if (!resolvedMessage &&
1047
- (!(isString(format) || isMessageFunction(format)) ||
1048
- !isString(targetLocale))) {
1049
- return unresolving ? NOT_REOSLVED : key;
1050
- }
1051
- if (isString(format) && context.messageCompiler == null) {
1052
- warn(`The message format compilation is not supported in this build. ` +
1053
- `Because message compiler isn't included. ` +
1054
- `You need to pre-compilation all message format. ` +
1055
- `So translate function return '${key}'.`);
1056
- return key;
1057
- }
1058
- // setup compile error detecting
1059
- let occurred = false;
1060
- const errorDetector = () => {
1061
- occurred = true;
1062
- };
1063
- // compile message format
1064
- const msg = !isMessageFunction(format)
1065
- ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
1066
- : format;
1067
- // if occurred compile error, return the message format
1068
- if (occurred) {
1069
- return format;
1070
- }
1071
- // evaluate message with context
1072
- const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
1073
- const msgContext = createMessageContext(ctxOptions);
1074
- const messaged = evaluateMessage(context, msg, msgContext);
1075
- // if use post translation option, proceed it with handler
1076
- const ret = postTranslation
1077
- ? postTranslation(messaged, key)
1078
- : messaged;
1079
- // NOTE: experimental !!
1080
- {
1081
- // prettier-ignore
1082
- const payloads = {
1083
- timestamp: Date.now(),
1084
- key: isString(key)
1085
- ? key
1086
- : isMessageFunction(format)
1087
- ? format.key
1088
- : '',
1089
- locale: targetLocale || (isMessageFunction(format)
1090
- ? format.locale
1091
- : ''),
1092
- format: isString(format)
1093
- ? format
1094
- : isMessageFunction(format)
1095
- ? format.source
1096
- : '',
1097
- message: ret
1098
- };
1099
- payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
1100
- translateDevTools(payloads);
1101
- }
1102
- return ret;
1103
- }
1104
- function escapeParams(options) {
1105
- if (isArray(options.list)) {
1106
- options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
1107
- }
1108
- else if (isObject(options.named)) {
1109
- Object.keys(options.named).forEach(key => {
1110
- if (isString(options.named[key])) {
1111
- options.named[key] = escapeHtml(options.named[key]);
1112
- }
1113
- });
1114
- }
1115
- }
1116
- function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
1117
- const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
1118
- const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
1119
- let message = {};
1120
- let targetLocale;
1121
- let format = null;
1122
- let from = locale;
1123
- let to = null;
1124
- const type = 'translate';
1125
- for (let i = 0; i < locales.length; i++) {
1126
- targetLocale = to = locales[i];
1127
- if (locale !== targetLocale &&
1128
- isTranslateFallbackWarn(fallbackWarn, key)) {
1129
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
1130
- key,
1131
- target: targetLocale
1132
- }));
1133
- }
1134
- // for vue-devtools timeline event
1135
- if (locale !== targetLocale) {
1136
- const emitter = context.__v_emitter;
1137
- if (emitter) {
1138
- emitter.emit("fallback" /* FALBACK */, {
1139
- type,
1140
- key,
1141
- from,
1142
- to,
1143
- groupId: `${type}:${key}`
1144
- });
1145
- }
1146
- }
1147
- message =
1148
- messages[targetLocale] || {};
1149
- // for vue-devtools timeline event
1150
- let start = null;
1151
- let startTag;
1152
- let endTag;
1153
- if (inBrowser) {
1154
- start = window.performance.now();
1155
- startTag = 'intlify-message-resolve-start';
1156
- endTag = 'intlify-message-resolve-end';
1157
- mark && mark(startTag);
1158
- }
1159
- if ((format = resolveValue(message, key)) === null) {
1160
- // if null, resolve with object key path
1161
- format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
1162
- }
1163
- // for vue-devtools timeline event
1164
- if (inBrowser) {
1165
- const end = window.performance.now();
1166
- const emitter = context.__v_emitter;
1167
- if (emitter && start && format) {
1168
- emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
1169
- type: "message-resolve" /* MESSAGE_RESOLVE */,
1170
- key,
1171
- message: format,
1172
- time: end - start,
1173
- groupId: `${type}:${key}`
1174
- });
1175
- }
1176
- if (startTag && endTag && mark && measure) {
1177
- mark(endTag);
1178
- measure('intlify message resolve', startTag, endTag);
1179
- }
1180
- }
1181
- if (isString(format) || isFunction(format))
1182
- break;
1183
- const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1184
- key, targetLocale, missingWarn, type);
1185
- if (missingRet !== key) {
1186
- format = missingRet;
1187
- }
1188
- from = to;
1189
- }
1190
- return [format, targetLocale, message];
1191
- }
1192
- function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
1193
- const { messageCompiler, warnHtmlMessage } = context;
1194
- if (isMessageFunction(format)) {
1195
- const msg = format;
1196
- msg.locale = msg.locale || targetLocale;
1197
- msg.key = msg.key || key;
1198
- return msg;
1199
- }
1200
- if (messageCompiler == null) {
1201
- const msg = (() => format);
1202
- msg.locale = targetLocale;
1203
- msg.key = key;
1204
- return msg;
1205
- }
1206
- // for vue-devtools timeline event
1207
- let start = null;
1208
- let startTag;
1209
- let endTag;
1210
- if (inBrowser) {
1211
- start = window.performance.now();
1212
- startTag = 'intlify-message-compilation-start';
1213
- endTag = 'intlify-message-compilation-end';
1214
- mark && mark(startTag);
1215
- }
1216
- const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
1217
- // for vue-devtools timeline event
1218
- if (inBrowser) {
1219
- const end = window.performance.now();
1220
- const emitter = context.__v_emitter;
1221
- if (emitter && start) {
1222
- emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
1223
- type: "message-compilation" /* MESSAGE_COMPILATION */,
1224
- message: format,
1225
- time: end - start,
1226
- groupId: `${'translate'}:${key}`
1227
- });
1228
- }
1229
- if (startTag && endTag && mark && measure) {
1230
- mark(endTag);
1231
- measure('intlify message compilation', startTag, endTag);
1232
- }
1233
- }
1234
- msg.locale = targetLocale;
1235
- msg.key = key;
1236
- msg.source = format;
1237
- return msg;
1238
- }
1239
- function evaluateMessage(context, msg, msgCtx) {
1240
- // for vue-devtools timeline event
1241
- let start = null;
1242
- let startTag;
1243
- let endTag;
1244
- if (inBrowser) {
1245
- start = window.performance.now();
1246
- startTag = 'intlify-message-evaluation-start';
1247
- endTag = 'intlify-message-evaluation-end';
1248
- mark && mark(startTag);
1249
- }
1250
- const messaged = msg(msgCtx);
1251
- // for vue-devtools timeline event
1252
- if (inBrowser) {
1253
- const end = window.performance.now();
1254
- const emitter = context.__v_emitter;
1255
- if (emitter && start) {
1256
- emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
1257
- type: "message-evaluation" /* MESSAGE_EVALUATION */,
1258
- value: messaged,
1259
- time: end - start,
1260
- groupId: `${'translate'}:${msg.key}`
1261
- });
1262
- }
1263
- if (startTag && endTag && mark && measure) {
1264
- mark(endTag);
1265
- measure('intlify message evaluation', startTag, endTag);
1266
- }
1267
- }
1268
- return messaged;
1269
- }
1270
- /** @internal */
1271
- function parseTranslateArgs(...args) {
1272
- const [arg1, arg2, arg3] = args;
1273
- const options = {};
1274
- if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
1275
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1276
- }
1277
- // prettier-ignore
1278
- const key = isNumber(arg1)
1279
- ? String(arg1)
1280
- : isMessageFunction(arg1)
1281
- ? arg1
1282
- : arg1;
1283
- if (isNumber(arg2)) {
1284
- options.plural = arg2;
1285
- }
1286
- else if (isString(arg2)) {
1287
- options.default = arg2;
1288
- }
1289
- else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
1290
- options.named = arg2;
1291
- }
1292
- else if (isArray(arg2)) {
1293
- options.list = arg2;
1294
- }
1295
- if (isNumber(arg3)) {
1296
- options.plural = arg3;
1297
- }
1298
- else if (isString(arg3)) {
1299
- options.default = arg3;
1300
- }
1301
- else if (isPlainObject(arg3)) {
1302
- assign(options, arg3);
1303
- }
1304
- return [key, options];
1305
- }
1306
- function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
1307
- return {
1308
- warnHtmlMessage,
1309
- onError: (err) => {
1310
- errorDetector && errorDetector(err);
1311
- {
1312
- const message = `Message compilation error: ${err.message}`;
1313
- const codeFrame = err.location &&
1314
- generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
1315
- const emitter = context.__v_emitter;
1316
- if (emitter) {
1317
- emitter.emit("compile-error" /* COMPILE_ERROR */, {
1318
- message: source,
1319
- error: err.message,
1320
- start: err.location && err.location.start.offset,
1321
- end: err.location && err.location.end.offset,
1322
- groupId: `${'translate'}:${key}`
1323
- });
1324
- }
1325
- console.error(codeFrame ? `${message}\n${codeFrame}` : message);
1326
- }
1327
- },
1328
- onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
1329
- };
1330
- }
1331
- function getMessageContextOptions(context, locale, message, options) {
1332
- const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
1333
- const resolveMessage = (key) => {
1334
- let val = resolveValue(message, key);
1335
- // fallback to root context
1336
- if (val == null && fallbackContext) {
1337
- const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
1338
- val = resolveValue(message, key);
1339
- }
1340
- if (isString(val)) {
1341
- let occurred = false;
1342
- const errorDetector = () => {
1343
- occurred = true;
1344
- };
1345
- const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
1346
- return !occurred
1347
- ? msg
1348
- : NOOP_MESSAGE_FUNCTION;
1349
- }
1350
- else if (isMessageFunction(val)) {
1351
- return val;
1352
- }
1353
- else {
1354
- // TODO: should be implemented warning message
1355
- return NOOP_MESSAGE_FUNCTION;
1356
- }
1357
- };
1358
- const ctxOptions = {
1359
- locale,
1360
- modifiers,
1361
- pluralRules,
1362
- messages: resolveMessage
1363
- };
1364
- if (context.processor) {
1365
- ctxOptions.processor = context.processor;
1366
- }
1367
- if (options.list) {
1368
- ctxOptions.list = options.list;
1369
- }
1370
- if (options.named) {
1371
- ctxOptions.named = options.named;
1372
- }
1373
- if (isNumber(options.plural)) {
1374
- ctxOptions.pluralIndex = options.plural;
1375
- }
1376
- return ctxOptions;
2408
+ const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
2409
+ function checkHtmlMessage(source, warnHtmlMessage) {
2410
+ if (warnHtmlMessage && detectHtmlTag(source)) {
2411
+ warn(format$1(WARN_MESSAGE, { source }));
2412
+ }
2413
+ }
2414
+ const defaultOnCacheKey = (message) => message;
2415
+ let compileCache = Object.create(null);
2416
+ function clearCompileCache() {
2417
+ compileCache = Object.create(null);
2418
+ }
2419
+ function baseCompile(message, options = {}) {
2420
+ // error detecting on compile
2421
+ let detectError = false;
2422
+ const onError = options.onError || defaultOnError;
2423
+ options.onError = (err) => {
2424
+ detectError = true;
2425
+ onError(err);
2426
+ };
2427
+ // compile with mesasge-compiler
2428
+ return { ...baseCompile$1(message, options), detectError };
2429
+ }
2430
+ function compileToFunction(message, options = {}) {
2431
+ if (!isString(message)) {
2432
+ throw createCoreError(CoreErrorCodes.NOT_SUPPORT_AST);
2433
+ }
2434
+ {
2435
+ warn(`Runtime compilation is not supported in ${'core.runtime.esm-browser.js' }.`);
2436
+ return (() => message);
2437
+ }
2438
+ }
2439
+ function compile(message, options = {}) {
2440
+ if (isString(message)) {
2441
+ // check HTML message
2442
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2443
+ const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
2444
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
2445
+ options.warnHtmlMessage
2446
+ : true;
2447
+ checkHtmlMessage(message, warnHtmlMessage);
2448
+ // check caches
2449
+ const onCacheKey = options.onCacheKey || defaultOnCacheKey;
2450
+ const cacheKey = onCacheKey(message);
2451
+ const cached = compileCache[cacheKey];
2452
+ if (cached) {
2453
+ return cached;
2454
+ }
2455
+ // compile with JIT mode
2456
+ const { ast, detectError } = baseCompile(message, {
2457
+ ...options,
2458
+ location: true,
2459
+ jit: true
2460
+ });
2461
+ // compose message function from AST
2462
+ const msg = format(ast);
2463
+ // if occurred compile error, don't cache
2464
+ return !detectError
2465
+ ? (compileCache[cacheKey] = msg)
2466
+ : msg;
2467
+ }
2468
+ else {
2469
+ // AST case (passed from bundler)
2470
+ const cacheKey = message.cacheKey;
2471
+ if (cacheKey) {
2472
+ const cached = compileCache[cacheKey];
2473
+ if (cached) {
2474
+ return cached;
2475
+ }
2476
+ // compose message function from message (AST)
2477
+ return (compileCache[cacheKey] =
2478
+ format(message));
2479
+ }
2480
+ else {
2481
+ return format(message);
2482
+ }
2483
+ }
2484
+ }
2485
+
2486
+ const NOOP_MESSAGE_FUNCTION = () => '';
2487
+ const isMessageFunction = (val) => isFunction(val);
2488
+ const isMessageAST = (val) => isObject(val) && val.type === 0 && 'body' in val;
2489
+ // implementation of `translate` function
2490
+ function translate(context, ...args) {
2491
+ const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
2492
+ const [key, options] = parseTranslateArgs(...args);
2493
+ const missingWarn = isBoolean(options.missingWarn)
2494
+ ? options.missingWarn
2495
+ : context.missingWarn;
2496
+ const fallbackWarn = isBoolean(options.fallbackWarn)
2497
+ ? options.fallbackWarn
2498
+ : context.fallbackWarn;
2499
+ const escapeParameter = isBoolean(options.escapeParameter)
2500
+ ? options.escapeParameter
2501
+ : context.escapeParameter;
2502
+ const resolvedMessage = !!options.resolvedMessage;
2503
+ // prettier-ignore
2504
+ const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
2505
+ ? !isBoolean(options.default)
2506
+ ? options.default
2507
+ : (!messageCompiler ? () => key : key)
2508
+ : fallbackFormat // default by `fallbackFormat` option
2509
+ ? (!messageCompiler ? () => key : key)
2510
+ : '';
2511
+ const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
2512
+ const locale = isString(options.locale) ? options.locale : context.locale;
2513
+ // escape params
2514
+ escapeParameter && escapeParams(options);
2515
+ // resolve message format
2516
+ // eslint-disable-next-line prefer-const
2517
+ let [formatScope, targetLocale, message] = !resolvedMessage
2518
+ ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
2519
+ : [
2520
+ key,
2521
+ locale,
2522
+ messages[locale] || {}
2523
+ ];
2524
+ // NOTE:
2525
+ // Fix to work around `ssrTransfrom` bug in Vite.
2526
+ // https://github.com/vitejs/vite/issues/4306
2527
+ // To get around this, use temporary variables.
2528
+ // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
2529
+ let format = formatScope;
2530
+ // if you use default message, set it as message format!
2531
+ let cacheBaseKey = key;
2532
+ if (!resolvedMessage &&
2533
+ !(isString(format) ||
2534
+ isMessageAST(format) ||
2535
+ isMessageFunction(format))) {
2536
+ if (enableDefaultMsg) {
2537
+ format = defaultMsgOrKey;
2538
+ cacheBaseKey = format;
2539
+ }
2540
+ }
2541
+ // checking message format and target locale
2542
+ if (!resolvedMessage &&
2543
+ (!(isString(format) ||
2544
+ isMessageAST(format) ||
2545
+ isMessageFunction(format)) ||
2546
+ !isString(targetLocale))) {
2547
+ return unresolving ? NOT_REOSLVED : key;
2548
+ }
2549
+ // TODO: refactor
2550
+ if (isString(format) && context.messageCompiler == null) {
2551
+ warn(`The message format compilation is not supported in this build. ` +
2552
+ `Because message compiler isn't included. ` +
2553
+ `You need to pre-compilation all message format. ` +
2554
+ `So translate function return '${key}'.`);
2555
+ return key;
2556
+ }
2557
+ // setup compile error detecting
2558
+ let occurred = false;
2559
+ const errorDetector = () => {
2560
+ occurred = true;
2561
+ };
2562
+ // compile message format
2563
+ const msg = !isMessageFunction(format)
2564
+ ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
2565
+ : format;
2566
+ // if occurred compile error, return the message format
2567
+ if (occurred) {
2568
+ return format;
2569
+ }
2570
+ // evaluate message with context
2571
+ const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
2572
+ const msgContext = createMessageContext(ctxOptions);
2573
+ const messaged = evaluateMessage(context, msg, msgContext);
2574
+ // if use post translation option, proceed it with handler
2575
+ const ret = postTranslation
2576
+ ? postTranslation(messaged, key)
2577
+ : messaged;
2578
+ // NOTE: experimental !!
2579
+ {
2580
+ // prettier-ignore
2581
+ const payloads = {
2582
+ timestamp: Date.now(),
2583
+ key: isString(key)
2584
+ ? key
2585
+ : isMessageFunction(format)
2586
+ ? format.key
2587
+ : '',
2588
+ locale: targetLocale || (isMessageFunction(format)
2589
+ ? format.locale
2590
+ : ''),
2591
+ format: isString(format)
2592
+ ? format
2593
+ : isMessageFunction(format)
2594
+ ? format.source
2595
+ : '',
2596
+ message: ret
2597
+ };
2598
+ payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
2599
+ translateDevTools(payloads);
2600
+ }
2601
+ return ret;
2602
+ }
2603
+ function escapeParams(options) {
2604
+ if (isArray(options.list)) {
2605
+ options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
2606
+ }
2607
+ else if (isObject(options.named)) {
2608
+ Object.keys(options.named).forEach(key => {
2609
+ if (isString(options.named[key])) {
2610
+ options.named[key] = escapeHtml(options.named[key]);
2611
+ }
2612
+ });
2613
+ }
2614
+ }
2615
+ function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
2616
+ const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
2617
+ const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
2618
+ let message = {};
2619
+ let targetLocale;
2620
+ let format = null;
2621
+ let from = locale;
2622
+ let to = null;
2623
+ const type = 'translate';
2624
+ for (let i = 0; i < locales.length; i++) {
2625
+ targetLocale = to = locales[i];
2626
+ if (locale !== targetLocale &&
2627
+ isTranslateFallbackWarn(fallbackWarn, key)) {
2628
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
2629
+ key,
2630
+ target: targetLocale
2631
+ }));
2632
+ }
2633
+ // for vue-devtools timeline event
2634
+ if (locale !== targetLocale) {
2635
+ const emitter = context.__v_emitter;
2636
+ if (emitter) {
2637
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
2638
+ type,
2639
+ key,
2640
+ from,
2641
+ to,
2642
+ groupId: `${type}:${key}`
2643
+ });
2644
+ }
2645
+ }
2646
+ message =
2647
+ messages[targetLocale] || {};
2648
+ // for vue-devtools timeline event
2649
+ let start = null;
2650
+ let startTag;
2651
+ let endTag;
2652
+ if (inBrowser) {
2653
+ start = window.performance.now();
2654
+ startTag = 'intlify-message-resolve-start';
2655
+ endTag = 'intlify-message-resolve-end';
2656
+ mark && mark(startTag);
2657
+ }
2658
+ if ((format = resolveValue(message, key)) === null) {
2659
+ // if null, resolve with object key path
2660
+ format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
2661
+ }
2662
+ // for vue-devtools timeline event
2663
+ if (inBrowser) {
2664
+ const end = window.performance.now();
2665
+ const emitter = context.__v_emitter;
2666
+ if (emitter && start && format) {
2667
+ emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
2668
+ type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
2669
+ key,
2670
+ message: format,
2671
+ time: end - start,
2672
+ groupId: `${type}:${key}`
2673
+ });
2674
+ }
2675
+ if (startTag && endTag && mark && measure) {
2676
+ mark(endTag);
2677
+ measure('intlify message resolve', startTag, endTag);
2678
+ }
2679
+ }
2680
+ if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
2681
+ break;
2682
+ }
2683
+ const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2684
+ key, targetLocale, missingWarn, type);
2685
+ if (missingRet !== key) {
2686
+ format = missingRet;
2687
+ }
2688
+ from = to;
2689
+ }
2690
+ return [format, targetLocale, message];
2691
+ }
2692
+ function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
2693
+ const { messageCompiler, warnHtmlMessage } = context;
2694
+ if (isMessageFunction(format)) {
2695
+ const msg = format;
2696
+ msg.locale = msg.locale || targetLocale;
2697
+ msg.key = msg.key || key;
2698
+ return msg;
2699
+ }
2700
+ if (messageCompiler == null) {
2701
+ const msg = (() => format);
2702
+ msg.locale = targetLocale;
2703
+ msg.key = key;
2704
+ return msg;
2705
+ }
2706
+ // for vue-devtools timeline event
2707
+ let start = null;
2708
+ let startTag;
2709
+ let endTag;
2710
+ if (inBrowser) {
2711
+ start = window.performance.now();
2712
+ startTag = 'intlify-message-compilation-start';
2713
+ endTag = 'intlify-message-compilation-end';
2714
+ mark && mark(startTag);
2715
+ }
2716
+ const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
2717
+ // for vue-devtools timeline event
2718
+ if (inBrowser) {
2719
+ const end = window.performance.now();
2720
+ const emitter = context.__v_emitter;
2721
+ if (emitter && start) {
2722
+ emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
2723
+ type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
2724
+ message: format,
2725
+ time: end - start,
2726
+ groupId: `${'translate'}:${key}`
2727
+ });
2728
+ }
2729
+ if (startTag && endTag && mark && measure) {
2730
+ mark(endTag);
2731
+ measure('intlify message compilation', startTag, endTag);
2732
+ }
2733
+ }
2734
+ msg.locale = targetLocale;
2735
+ msg.key = key;
2736
+ msg.source = format;
2737
+ return msg;
2738
+ }
2739
+ function evaluateMessage(context, msg, msgCtx) {
2740
+ // for vue-devtools timeline event
2741
+ let start = null;
2742
+ let startTag;
2743
+ let endTag;
2744
+ if (inBrowser) {
2745
+ start = window.performance.now();
2746
+ startTag = 'intlify-message-evaluation-start';
2747
+ endTag = 'intlify-message-evaluation-end';
2748
+ mark && mark(startTag);
2749
+ }
2750
+ const messaged = msg(msgCtx);
2751
+ // for vue-devtools timeline event
2752
+ if (inBrowser) {
2753
+ const end = window.performance.now();
2754
+ const emitter = context.__v_emitter;
2755
+ if (emitter && start) {
2756
+ emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
2757
+ type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
2758
+ value: messaged,
2759
+ time: end - start,
2760
+ groupId: `${'translate'}:${msg.key}`
2761
+ });
2762
+ }
2763
+ if (startTag && endTag && mark && measure) {
2764
+ mark(endTag);
2765
+ measure('intlify message evaluation', startTag, endTag);
2766
+ }
2767
+ }
2768
+ return messaged;
2769
+ }
2770
+ /** @internal */
2771
+ function parseTranslateArgs(...args) {
2772
+ const [arg1, arg2, arg3] = args;
2773
+ const options = {};
2774
+ if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
2775
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
2776
+ }
2777
+ // prettier-ignore
2778
+ const key = isNumber(arg1)
2779
+ ? String(arg1)
2780
+ : isMessageFunction(arg1)
2781
+ ? arg1
2782
+ : arg1;
2783
+ if (isNumber(arg2)) {
2784
+ options.plural = arg2;
2785
+ }
2786
+ else if (isString(arg2)) {
2787
+ options.default = arg2;
2788
+ }
2789
+ else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
2790
+ options.named = arg2;
2791
+ }
2792
+ else if (isArray(arg2)) {
2793
+ options.list = arg2;
2794
+ }
2795
+ if (isNumber(arg3)) {
2796
+ options.plural = arg3;
2797
+ }
2798
+ else if (isString(arg3)) {
2799
+ options.default = arg3;
2800
+ }
2801
+ else if (isPlainObject(arg3)) {
2802
+ assign(options, arg3);
2803
+ }
2804
+ return [key, options];
2805
+ }
2806
+ function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
2807
+ return {
2808
+ warnHtmlMessage,
2809
+ onError: (err) => {
2810
+ errorDetector && errorDetector(err);
2811
+ {
2812
+ const _source = getSourceForCodeFrame(source);
2813
+ const message = `Message compilation error: ${err.message}`;
2814
+ const codeFrame = err.location &&
2815
+ _source &&
2816
+ generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
2817
+ const emitter = context.__v_emitter;
2818
+ if (emitter && _source) {
2819
+ emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
2820
+ message: _source,
2821
+ error: err.message,
2822
+ start: err.location && err.location.start.offset,
2823
+ end: err.location && err.location.end.offset,
2824
+ groupId: `${'translate'}:${key}`
2825
+ });
2826
+ }
2827
+ console.error(codeFrame ? `${message}\n${codeFrame}` : message);
2828
+ }
2829
+ },
2830
+ onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
2831
+ };
2832
+ }
2833
+ function getSourceForCodeFrame(source) {
2834
+ if (isString(source)) ;
2835
+ else {
2836
+ if (source.loc?.source) {
2837
+ return source.loc.source;
2838
+ }
2839
+ }
2840
+ }
2841
+ function getMessageContextOptions(context, locale, message, options) {
2842
+ const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
2843
+ const resolveMessage = (key) => {
2844
+ let val = resolveValue(message, key);
2845
+ // fallback to root context
2846
+ if (val == null && fallbackContext) {
2847
+ const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
2848
+ val = resolveValue(message, key);
2849
+ }
2850
+ if (isString(val) || isMessageAST(val)) {
2851
+ let occurred = false;
2852
+ const errorDetector = () => {
2853
+ occurred = true;
2854
+ };
2855
+ const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
2856
+ return !occurred
2857
+ ? msg
2858
+ : NOOP_MESSAGE_FUNCTION;
2859
+ }
2860
+ else if (isMessageFunction(val)) {
2861
+ return val;
2862
+ }
2863
+ else {
2864
+ // TODO: should be implemented warning message
2865
+ return NOOP_MESSAGE_FUNCTION;
2866
+ }
2867
+ };
2868
+ const ctxOptions = {
2869
+ locale,
2870
+ modifiers,
2871
+ pluralRules,
2872
+ messages: resolveMessage
2873
+ };
2874
+ if (context.processor) {
2875
+ ctxOptions.processor = context.processor;
2876
+ }
2877
+ if (options.list) {
2878
+ ctxOptions.list = options.list;
2879
+ }
2880
+ if (options.named) {
2881
+ ctxOptions.named = options.named;
2882
+ }
2883
+ if (isNumber(options.plural)) {
2884
+ ctxOptions.pluralIndex = options.plural;
2885
+ }
2886
+ return ctxOptions;
1377
2887
  }
1378
2888
 
1379
- const intlDefined = typeof Intl !== 'undefined';
1380
- const Availabilities = {
1381
- dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
1382
- numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
2889
+ const intlDefined = typeof Intl !== 'undefined';
2890
+ const Availabilities = {
2891
+ dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
2892
+ numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
1383
2893
  };
1384
2894
 
1385
- // implementation of `datetime` function
1386
- function datetime(context, ...args) {
1387
- const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1388
- const { __datetimeFormatters } = context;
1389
- if (!Availabilities.dateTimeFormat) {
1390
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
1391
- return MISSING_RESOLVE_VALUE;
1392
- }
1393
- const [key, value, options, overrides] = parseDateTimeArgs(...args);
1394
- const missingWarn = isBoolean(options.missingWarn)
1395
- ? options.missingWarn
1396
- : context.missingWarn;
1397
- const fallbackWarn = isBoolean(options.fallbackWarn)
1398
- ? options.fallbackWarn
1399
- : context.fallbackWarn;
1400
- const part = !!options.part;
1401
- const locale = isString(options.locale) ? options.locale : context.locale;
1402
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1403
- fallbackLocale, locale);
1404
- if (!isString(key) || key === '') {
1405
- return new Intl.DateTimeFormat(locale, overrides).format(value);
1406
- }
1407
- // resolve format
1408
- let datetimeFormat = {};
1409
- let targetLocale;
1410
- let format = null;
1411
- let from = locale;
1412
- let to = null;
1413
- const type = 'datetime format';
1414
- for (let i = 0; i < locales.length; i++) {
1415
- targetLocale = to = locales[i];
1416
- if (locale !== targetLocale &&
1417
- isTranslateFallbackWarn(fallbackWarn, key)) {
1418
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
1419
- key,
1420
- target: targetLocale
1421
- }));
1422
- }
1423
- // for vue-devtools timeline event
1424
- if (locale !== targetLocale) {
1425
- const emitter = context.__v_emitter;
1426
- if (emitter) {
1427
- emitter.emit("fallback" /* FALBACK */, {
1428
- type,
1429
- key,
1430
- from,
1431
- to,
1432
- groupId: `${type}:${key}`
1433
- });
1434
- }
1435
- }
1436
- datetimeFormat =
1437
- datetimeFormats[targetLocale] || {};
1438
- format = datetimeFormat[key];
1439
- if (isPlainObject(format))
1440
- break;
1441
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1442
- from = to;
1443
- }
1444
- // checking format and target locale
1445
- if (!isPlainObject(format) || !isString(targetLocale)) {
1446
- return unresolving ? NOT_REOSLVED : key;
1447
- }
1448
- let id = `${targetLocale}__${key}`;
1449
- if (!isEmptyObject(overrides)) {
1450
- id = `${id}__${JSON.stringify(overrides)}`;
1451
- }
1452
- let formatter = __datetimeFormatters.get(id);
1453
- if (!formatter) {
1454
- formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
1455
- __datetimeFormatters.set(id, formatter);
1456
- }
1457
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1458
- }
1459
- /** @internal */
1460
- const DATETIME_FORMAT_OPTIONS_KEYS = [
1461
- 'localeMatcher',
1462
- 'weekday',
1463
- 'era',
1464
- 'year',
1465
- 'month',
1466
- 'day',
1467
- 'hour',
1468
- 'minute',
1469
- 'second',
1470
- 'timeZoneName',
1471
- 'formatMatcher',
1472
- 'hour12',
1473
- 'timeZone',
1474
- 'dateStyle',
1475
- 'timeStyle',
1476
- 'calendar',
1477
- 'dayPeriod',
1478
- 'numberingSystem',
1479
- 'hourCycle',
1480
- 'fractionalSecondDigits'
1481
- ];
1482
- /** @internal */
1483
- function parseDateTimeArgs(...args) {
1484
- const [arg1, arg2, arg3, arg4] = args;
1485
- const options = {};
1486
- let overrides = {};
1487
- let value;
1488
- if (isString(arg1)) {
1489
- // Only allow ISO strings - other date formats are often supported,
1490
- // but may cause different results in different browsers.
1491
- const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
1492
- if (!matches) {
1493
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1494
- }
1495
- // Some browsers can not parse the iso datetime separated by space,
1496
- // this is a compromise solution by replace the 'T'/' ' with 'T'
1497
- const dateTime = matches[3]
1498
- ? matches[3].trim().startsWith('T')
1499
- ? `${matches[1].trim()}${matches[3].trim()}`
1500
- : `${matches[1].trim()}T${matches[3].trim()}`
1501
- : matches[1].trim();
1502
- value = new Date(dateTime);
1503
- try {
1504
- // This will fail if the date is not valid
1505
- value.toISOString();
1506
- }
1507
- catch (e) {
1508
- throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
1509
- }
1510
- }
1511
- else if (isDate(arg1)) {
1512
- if (isNaN(arg1.getTime())) {
1513
- throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
1514
- }
1515
- value = arg1;
1516
- }
1517
- else if (isNumber(arg1)) {
1518
- value = arg1;
1519
- }
1520
- else {
1521
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1522
- }
1523
- if (isString(arg2)) {
1524
- options.key = arg2;
1525
- }
1526
- else if (isPlainObject(arg2)) {
1527
- Object.keys(arg2).forEach(key => {
1528
- if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
1529
- overrides[key] = arg2[key];
1530
- }
1531
- else {
1532
- options[key] = arg2[key];
1533
- }
1534
- });
1535
- }
1536
- if (isString(arg3)) {
1537
- options.locale = arg3;
1538
- }
1539
- else if (isPlainObject(arg3)) {
1540
- overrides = arg3;
1541
- }
1542
- if (isPlainObject(arg4)) {
1543
- overrides = arg4;
1544
- }
1545
- return [options.key || '', value, options, overrides];
1546
- }
1547
- /** @internal */
1548
- function clearDateTimeFormat(ctx, locale, format) {
1549
- const context = ctx;
1550
- for (const key in format) {
1551
- const id = `${locale}__${key}`;
1552
- if (!context.__datetimeFormatters.has(id)) {
1553
- continue;
1554
- }
1555
- context.__datetimeFormatters.delete(id);
1556
- }
2895
+ // implementation of `datetime` function
2896
+ function datetime(context, ...args) {
2897
+ const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
2898
+ const { __datetimeFormatters } = context;
2899
+ if (!Availabilities.dateTimeFormat) {
2900
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));
2901
+ return MISSING_RESOLVE_VALUE;
2902
+ }
2903
+ const [key, value, options, overrides] = parseDateTimeArgs(...args);
2904
+ const missingWarn = isBoolean(options.missingWarn)
2905
+ ? options.missingWarn
2906
+ : context.missingWarn;
2907
+ const fallbackWarn = isBoolean(options.fallbackWarn)
2908
+ ? options.fallbackWarn
2909
+ : context.fallbackWarn;
2910
+ const part = !!options.part;
2911
+ const locale = isString(options.locale) ? options.locale : context.locale;
2912
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
2913
+ fallbackLocale, locale);
2914
+ if (!isString(key) || key === '') {
2915
+ return new Intl.DateTimeFormat(locale, overrides).format(value);
2916
+ }
2917
+ // resolve format
2918
+ let datetimeFormat = {};
2919
+ let targetLocale;
2920
+ let format = null;
2921
+ let from = locale;
2922
+ let to = null;
2923
+ const type = 'datetime format';
2924
+ for (let i = 0; i < locales.length; i++) {
2925
+ targetLocale = to = locales[i];
2926
+ if (locale !== targetLocale &&
2927
+ isTranslateFallbackWarn(fallbackWarn, key)) {
2928
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
2929
+ key,
2930
+ target: targetLocale
2931
+ }));
2932
+ }
2933
+ // for vue-devtools timeline event
2934
+ if (locale !== targetLocale) {
2935
+ const emitter = context.__v_emitter;
2936
+ if (emitter) {
2937
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
2938
+ type,
2939
+ key,
2940
+ from,
2941
+ to,
2942
+ groupId: `${type}:${key}`
2943
+ });
2944
+ }
2945
+ }
2946
+ datetimeFormat =
2947
+ datetimeFormats[targetLocale] || {};
2948
+ format = datetimeFormat[key];
2949
+ if (isPlainObject(format))
2950
+ break;
2951
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
2952
+ from = to;
2953
+ }
2954
+ // checking format and target locale
2955
+ if (!isPlainObject(format) || !isString(targetLocale)) {
2956
+ return unresolving ? NOT_REOSLVED : key;
2957
+ }
2958
+ let id = `${targetLocale}__${key}`;
2959
+ if (!isEmptyObject(overrides)) {
2960
+ id = `${id}__${JSON.stringify(overrides)}`;
2961
+ }
2962
+ let formatter = __datetimeFormatters.get(id);
2963
+ if (!formatter) {
2964
+ formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
2965
+ __datetimeFormatters.set(id, formatter);
2966
+ }
2967
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
2968
+ }
2969
+ /** @internal */
2970
+ const DATETIME_FORMAT_OPTIONS_KEYS = [
2971
+ 'localeMatcher',
2972
+ 'weekday',
2973
+ 'era',
2974
+ 'year',
2975
+ 'month',
2976
+ 'day',
2977
+ 'hour',
2978
+ 'minute',
2979
+ 'second',
2980
+ 'timeZoneName',
2981
+ 'formatMatcher',
2982
+ 'hour12',
2983
+ 'timeZone',
2984
+ 'dateStyle',
2985
+ 'timeStyle',
2986
+ 'calendar',
2987
+ 'dayPeriod',
2988
+ 'numberingSystem',
2989
+ 'hourCycle',
2990
+ 'fractionalSecondDigits'
2991
+ ];
2992
+ /** @internal */
2993
+ function parseDateTimeArgs(...args) {
2994
+ const [arg1, arg2, arg3, arg4] = args;
2995
+ const options = {};
2996
+ let overrides = {};
2997
+ let value;
2998
+ if (isString(arg1)) {
2999
+ // Only allow ISO strings - other date formats are often supported,
3000
+ // but may cause different results in different browsers.
3001
+ const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
3002
+ if (!matches) {
3003
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3004
+ }
3005
+ // Some browsers can not parse the iso datetime separated by space,
3006
+ // this is a compromise solution by replace the 'T'/' ' with 'T'
3007
+ const dateTime = matches[3]
3008
+ ? matches[3].trim().startsWith('T')
3009
+ ? `${matches[1].trim()}${matches[3].trim()}`
3010
+ : `${matches[1].trim()}T${matches[3].trim()}`
3011
+ : matches[1].trim();
3012
+ value = new Date(dateTime);
3013
+ try {
3014
+ // This will fail if the date is not valid
3015
+ value.toISOString();
3016
+ }
3017
+ catch (e) {
3018
+ throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
3019
+ }
3020
+ }
3021
+ else if (isDate(arg1)) {
3022
+ if (isNaN(arg1.getTime())) {
3023
+ throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
3024
+ }
3025
+ value = arg1;
3026
+ }
3027
+ else if (isNumber(arg1)) {
3028
+ value = arg1;
3029
+ }
3030
+ else {
3031
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3032
+ }
3033
+ if (isString(arg2)) {
3034
+ options.key = arg2;
3035
+ }
3036
+ else if (isPlainObject(arg2)) {
3037
+ Object.keys(arg2).forEach(key => {
3038
+ if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
3039
+ overrides[key] = arg2[key];
3040
+ }
3041
+ else {
3042
+ options[key] = arg2[key];
3043
+ }
3044
+ });
3045
+ }
3046
+ if (isString(arg3)) {
3047
+ options.locale = arg3;
3048
+ }
3049
+ else if (isPlainObject(arg3)) {
3050
+ overrides = arg3;
3051
+ }
3052
+ if (isPlainObject(arg4)) {
3053
+ overrides = arg4;
3054
+ }
3055
+ return [options.key || '', value, options, overrides];
3056
+ }
3057
+ /** @internal */
3058
+ function clearDateTimeFormat(ctx, locale, format) {
3059
+ const context = ctx;
3060
+ for (const key in format) {
3061
+ const id = `${locale}__${key}`;
3062
+ if (!context.__datetimeFormatters.has(id)) {
3063
+ continue;
3064
+ }
3065
+ context.__datetimeFormatters.delete(id);
3066
+ }
1557
3067
  }
1558
3068
 
1559
- // implementation of `number` function
1560
- function number(context, ...args) {
1561
- const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
1562
- const { __numberFormatters } = context;
1563
- if (!Availabilities.numberFormat) {
1564
- onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
1565
- return MISSING_RESOLVE_VALUE;
1566
- }
1567
- const [key, value, options, overrides] = parseNumberArgs(...args);
1568
- const missingWarn = isBoolean(options.missingWarn)
1569
- ? options.missingWarn
1570
- : context.missingWarn;
1571
- const fallbackWarn = isBoolean(options.fallbackWarn)
1572
- ? options.fallbackWarn
1573
- : context.fallbackWarn;
1574
- const part = !!options.part;
1575
- const locale = isString(options.locale) ? options.locale : context.locale;
1576
- const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
1577
- fallbackLocale, locale);
1578
- if (!isString(key) || key === '') {
1579
- return new Intl.NumberFormat(locale, overrides).format(value);
1580
- }
1581
- // resolve format
1582
- let numberFormat = {};
1583
- let targetLocale;
1584
- let format = null;
1585
- let from = locale;
1586
- let to = null;
1587
- const type = 'number format';
1588
- for (let i = 0; i < locales.length; i++) {
1589
- targetLocale = to = locales[i];
1590
- if (locale !== targetLocale &&
1591
- isTranslateFallbackWarn(fallbackWarn, key)) {
1592
- onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
1593
- key,
1594
- target: targetLocale
1595
- }));
1596
- }
1597
- // for vue-devtools timeline event
1598
- if (locale !== targetLocale) {
1599
- const emitter = context.__v_emitter;
1600
- if (emitter) {
1601
- emitter.emit("fallback" /* FALBACK */, {
1602
- type,
1603
- key,
1604
- from,
1605
- to,
1606
- groupId: `${type}:${key}`
1607
- });
1608
- }
1609
- }
1610
- numberFormat =
1611
- numberFormats[targetLocale] || {};
1612
- format = numberFormat[key];
1613
- if (isPlainObject(format))
1614
- break;
1615
- handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
1616
- from = to;
1617
- }
1618
- // checking format and target locale
1619
- if (!isPlainObject(format) || !isString(targetLocale)) {
1620
- return unresolving ? NOT_REOSLVED : key;
1621
- }
1622
- let id = `${targetLocale}__${key}`;
1623
- if (!isEmptyObject(overrides)) {
1624
- id = `${id}__${JSON.stringify(overrides)}`;
1625
- }
1626
- let formatter = __numberFormatters.get(id);
1627
- if (!formatter) {
1628
- formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
1629
- __numberFormatters.set(id, formatter);
1630
- }
1631
- return !part ? formatter.format(value) : formatter.formatToParts(value);
1632
- }
1633
- /** @internal */
1634
- const NUMBER_FORMAT_OPTIONS_KEYS = [
1635
- 'localeMatcher',
1636
- 'style',
1637
- 'currency',
1638
- 'currencyDisplay',
1639
- 'currencySign',
1640
- 'useGrouping',
1641
- 'minimumIntegerDigits',
1642
- 'minimumFractionDigits',
1643
- 'maximumFractionDigits',
1644
- 'minimumSignificantDigits',
1645
- 'maximumSignificantDigits',
1646
- 'compactDisplay',
1647
- 'notation',
1648
- 'signDisplay',
1649
- 'unit',
1650
- 'unitDisplay',
1651
- 'roundingMode',
1652
- 'roundingPriority',
1653
- 'roundingIncrement',
1654
- 'trailingZeroDisplay'
1655
- ];
1656
- /** @internal */
1657
- function parseNumberArgs(...args) {
1658
- const [arg1, arg2, arg3, arg4] = args;
1659
- const options = {};
1660
- let overrides = {};
1661
- if (!isNumber(arg1)) {
1662
- throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
1663
- }
1664
- const value = arg1;
1665
- if (isString(arg2)) {
1666
- options.key = arg2;
1667
- }
1668
- else if (isPlainObject(arg2)) {
1669
- Object.keys(arg2).forEach(key => {
1670
- if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
1671
- overrides[key] = arg2[key];
1672
- }
1673
- else {
1674
- options[key] = arg2[key];
1675
- }
1676
- });
1677
- }
1678
- if (isString(arg3)) {
1679
- options.locale = arg3;
1680
- }
1681
- else if (isPlainObject(arg3)) {
1682
- overrides = arg3;
1683
- }
1684
- if (isPlainObject(arg4)) {
1685
- overrides = arg4;
1686
- }
1687
- return [options.key || '', value, options, overrides];
1688
- }
1689
- /** @internal */
1690
- function clearNumberFormat(ctx, locale, format) {
1691
- const context = ctx;
1692
- for (const key in format) {
1693
- const id = `${locale}__${key}`;
1694
- if (!context.__numberFormatters.has(id)) {
1695
- continue;
1696
- }
1697
- context.__numberFormatters.delete(id);
1698
- }
3069
+ // implementation of `number` function
3070
+ function number(context, ...args) {
3071
+ const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
3072
+ const { __numberFormatters } = context;
3073
+ if (!Availabilities.numberFormat) {
3074
+ onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
3075
+ return MISSING_RESOLVE_VALUE;
3076
+ }
3077
+ const [key, value, options, overrides] = parseNumberArgs(...args);
3078
+ const missingWarn = isBoolean(options.missingWarn)
3079
+ ? options.missingWarn
3080
+ : context.missingWarn;
3081
+ const fallbackWarn = isBoolean(options.fallbackWarn)
3082
+ ? options.fallbackWarn
3083
+ : context.fallbackWarn;
3084
+ const part = !!options.part;
3085
+ const locale = isString(options.locale) ? options.locale : context.locale;
3086
+ const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
3087
+ fallbackLocale, locale);
3088
+ if (!isString(key) || key === '') {
3089
+ return new Intl.NumberFormat(locale, overrides).format(value);
3090
+ }
3091
+ // resolve format
3092
+ let numberFormat = {};
3093
+ let targetLocale;
3094
+ let format = null;
3095
+ let from = locale;
3096
+ let to = null;
3097
+ const type = 'number format';
3098
+ for (let i = 0; i < locales.length; i++) {
3099
+ targetLocale = to = locales[i];
3100
+ if (locale !== targetLocale &&
3101
+ isTranslateFallbackWarn(fallbackWarn, key)) {
3102
+ onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
3103
+ key,
3104
+ target: targetLocale
3105
+ }));
3106
+ }
3107
+ // for vue-devtools timeline event
3108
+ if (locale !== targetLocale) {
3109
+ const emitter = context.__v_emitter;
3110
+ if (emitter) {
3111
+ emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
3112
+ type,
3113
+ key,
3114
+ from,
3115
+ to,
3116
+ groupId: `${type}:${key}`
3117
+ });
3118
+ }
3119
+ }
3120
+ numberFormat =
3121
+ numberFormats[targetLocale] || {};
3122
+ format = numberFormat[key];
3123
+ if (isPlainObject(format))
3124
+ break;
3125
+ handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
3126
+ from = to;
3127
+ }
3128
+ // checking format and target locale
3129
+ if (!isPlainObject(format) || !isString(targetLocale)) {
3130
+ return unresolving ? NOT_REOSLVED : key;
3131
+ }
3132
+ let id = `${targetLocale}__${key}`;
3133
+ if (!isEmptyObject(overrides)) {
3134
+ id = `${id}__${JSON.stringify(overrides)}`;
3135
+ }
3136
+ let formatter = __numberFormatters.get(id);
3137
+ if (!formatter) {
3138
+ formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
3139
+ __numberFormatters.set(id, formatter);
3140
+ }
3141
+ return !part ? formatter.format(value) : formatter.formatToParts(value);
3142
+ }
3143
+ /** @internal */
3144
+ const NUMBER_FORMAT_OPTIONS_KEYS = [
3145
+ 'localeMatcher',
3146
+ 'style',
3147
+ 'currency',
3148
+ 'currencyDisplay',
3149
+ 'currencySign',
3150
+ 'useGrouping',
3151
+ 'minimumIntegerDigits',
3152
+ 'minimumFractionDigits',
3153
+ 'maximumFractionDigits',
3154
+ 'minimumSignificantDigits',
3155
+ 'maximumSignificantDigits',
3156
+ 'compactDisplay',
3157
+ 'notation',
3158
+ 'signDisplay',
3159
+ 'unit',
3160
+ 'unitDisplay',
3161
+ 'roundingMode',
3162
+ 'roundingPriority',
3163
+ 'roundingIncrement',
3164
+ 'trailingZeroDisplay'
3165
+ ];
3166
+ /** @internal */
3167
+ function parseNumberArgs(...args) {
3168
+ const [arg1, arg2, arg3, arg4] = args;
3169
+ const options = {};
3170
+ let overrides = {};
3171
+ if (!isNumber(arg1)) {
3172
+ throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
3173
+ }
3174
+ const value = arg1;
3175
+ if (isString(arg2)) {
3176
+ options.key = arg2;
3177
+ }
3178
+ else if (isPlainObject(arg2)) {
3179
+ Object.keys(arg2).forEach(key => {
3180
+ if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
3181
+ overrides[key] = arg2[key];
3182
+ }
3183
+ else {
3184
+ options[key] = arg2[key];
3185
+ }
3186
+ });
3187
+ }
3188
+ if (isString(arg3)) {
3189
+ options.locale = arg3;
3190
+ }
3191
+ else if (isPlainObject(arg3)) {
3192
+ overrides = arg3;
3193
+ }
3194
+ if (isPlainObject(arg4)) {
3195
+ overrides = arg4;
3196
+ }
3197
+ return [options.key || '', value, options, overrides];
3198
+ }
3199
+ /** @internal */
3200
+ function clearNumberFormat(ctx, locale, format) {
3201
+ const context = ctx;
3202
+ for (const key in format) {
3203
+ const id = `${locale}__${key}`;
3204
+ if (!context.__numberFormatters.has(id)) {
3205
+ continue;
3206
+ }
3207
+ context.__numberFormatters.delete(id);
3208
+ }
1699
3209
  }
1700
3210
 
1701
- // register message resolver at @intlify/core
1702
- registerMessageResolver(resolveValue);
1703
- // register fallback locale at @intlify/core
3211
+ // register message resolver at @intlify/core
3212
+ registerMessageResolver(resolveValue);
3213
+ // register fallback locale at @intlify/core
1704
3214
  registerLocaleFallbacker(fallbackWithLocaleChain);
1705
3215
 
1706
- export { CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compileToFunction, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getWarnMessage, handleMissing, initI18nDevTools, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };
3216
+ export { CompileErrorCodes, CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, compileToFunction, createCompileError, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getWarnMessage, handleMissing, initI18nDevTools, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };