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