@intlify/core 9.3.0-beta.9 → 9.4.0

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