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

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