@intlify/core 9.2.0-beta.10

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