1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | var VueI18nBridge = (function (exports, compositionApi) {
|
7 | 'use strict';
|
8 |
|
9 | |
10 |
|
11 |
|
12 |
|
13 | const inBrowser = typeof window !== 'undefined';
|
14 | let mark;
|
15 | {
|
16 | const perf = inBrowser && window.performance;
|
17 | if (perf &&
|
18 | perf.mark &&
|
19 | perf.measure &&
|
20 | perf.clearMarks &&
|
21 | perf.clearMeasures) {
|
22 | mark = (tag) => perf.mark(tag);
|
23 | }
|
24 | }
|
25 | const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
|
26 |
|
27 | function format(message, ...args) {
|
28 | if (args.length === 1 && isObject(args[0])) {
|
29 | args = args[0];
|
30 | }
|
31 | if (!args || !args.hasOwnProperty) {
|
32 | args = {};
|
33 | }
|
34 | return message.replace(RE_ARGS, (match, identifier) => {
|
35 | return args.hasOwnProperty(identifier) ? args[identifier] : '';
|
36 | });
|
37 | }
|
38 | const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
|
39 | const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
|
40 | const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
|
41 | const friendlyJSONstringify = (json) => JSON.stringify(json)
|
42 | .replace(/\u2028/g, '\\u2028')
|
43 | .replace(/\u2029/g, '\\u2029')
|
44 | .replace(/\u0027/g, '\\u0027');
|
45 | const isNumber = (val) => typeof val === 'number' && isFinite(val);
|
46 | const isDate = (val) => toTypeString(val) === '[object Date]';
|
47 | const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
|
48 | const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
|
49 | function warn(msg, err) {
|
50 | if (typeof console !== 'undefined') {
|
51 | console.warn(`[intlify] ` + msg);
|
52 |
|
53 | if (err) {
|
54 | console.warn(err.stack);
|
55 | }
|
56 | }
|
57 | }
|
58 | const assign = Object.assign;
|
59 | let _globalThis;
|
60 | const getGlobalThis = () => {
|
61 |
|
62 | return (_globalThis ||
|
63 | (_globalThis =
|
64 | typeof globalThis !== 'undefined'
|
65 | ? globalThis
|
66 | : typeof self !== 'undefined'
|
67 | ? self
|
68 | : typeof window !== 'undefined'
|
69 | ? window
|
70 | : typeof global !== 'undefined'
|
71 | ? global
|
72 | : {}));
|
73 | };
|
74 | function escapeHtml(rawText) {
|
75 | return rawText
|
76 | .replace(/</g, '<')
|
77 | .replace(/>/g, '>')
|
78 | .replace(/"/g, '"')
|
79 | .replace(/'/g, ''');
|
80 | }
|
81 | const hasOwnProperty = Object.prototype.hasOwnProperty;
|
82 | function hasOwn(obj, key) {
|
83 | return hasOwnProperty.call(obj, key);
|
84 | }
|
85 |
|
86 | |
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | const isArray = Array.isArray;
|
94 | const isFunction = (val) => typeof val === 'function';
|
95 | const isString = (val) => typeof val === 'string';
|
96 | const isBoolean = (val) => typeof val === 'boolean';
|
97 | const isObject = (val) =>
|
98 | val !== null && typeof val === 'object';
|
99 | const objectToString = Object.prototype.toString;
|
100 | const toTypeString = (value) => objectToString.call(value);
|
101 | const isPlainObject = (val) => toTypeString(val) === '[object Object]';
|
102 |
|
103 | const toDisplayString = (val) => {
|
104 | return val == null
|
105 | ? ''
|
106 | : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
|
107 | ? JSON.stringify(val, null, 2)
|
108 | : String(val);
|
109 | };
|
110 |
|
111 | const CompileErrorCodes = {
|
112 |
|
113 | EXPECTED_TOKEN: 1,
|
114 | INVALID_TOKEN_IN_PLACEHOLDER: 2,
|
115 | UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
|
116 | UNKNOWN_ESCAPE_SEQUENCE: 4,
|
117 | INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
|
118 | UNBALANCED_CLOSING_BRACE: 6,
|
119 | UNTERMINATED_CLOSING_BRACE: 7,
|
120 | EMPTY_PLACEHOLDER: 8,
|
121 | NOT_ALLOW_NEST_PLACEHOLDER: 9,
|
122 | INVALID_LINKED_FORMAT: 10,
|
123 |
|
124 | MUST_HAVE_MESSAGES_IN_PLURAL: 11,
|
125 | UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
|
126 | UNEXPECTED_EMPTY_LINKED_KEY: 13,
|
127 | UNEXPECTED_LEXICAL_ANALYSIS: 14,
|
128 |
|
129 |
|
130 |
|
131 | __EXTEND_POINT__: 15
|
132 | };
|
133 |
|
134 | const errorMessages$2 = {
|
135 |
|
136 | [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
|
137 | [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
|
138 | [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
|
139 | [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
|
140 | [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
|
141 | [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
|
142 | [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
|
143 | [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
|
144 | [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
|
145 | [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
|
146 |
|
147 | [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
|
148 | [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
|
149 | [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
|
150 | [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
|
151 | };
|
152 | function createCompileError(code, loc, options = {}) {
|
153 | const { domain, messages, args } = options;
|
154 | const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
|
155 | ;
|
156 | const error = new SyntaxError(String(msg));
|
157 | error.code = code;
|
158 | if (loc) {
|
159 | error.location = loc;
|
160 | }
|
161 | error.domain = domain;
|
162 | return error;
|
163 | }
|
164 |
|
165 | function defaultOnError(error) {
|
166 | throw error;
|
167 | }
|
168 |
|
169 | function createPosition(line, column, offset) {
|
170 | return { line, column, offset };
|
171 | }
|
172 | function createLocation(start, end, source) {
|
173 | const loc = { start, end };
|
174 | if (source != null) {
|
175 | loc.source = source;
|
176 | }
|
177 | return loc;
|
178 | }
|
179 |
|
180 | const CHAR_SP = ' ';
|
181 | const CHAR_CR = '\r';
|
182 | const CHAR_LF = '\n';
|
183 | const CHAR_LS = String.fromCharCode(0x2028);
|
184 | const CHAR_PS = String.fromCharCode(0x2029);
|
185 | function createScanner(str) {
|
186 | const _buf = str;
|
187 | let _index = 0;
|
188 | let _line = 1;
|
189 | let _column = 1;
|
190 | let _peekOffset = 0;
|
191 | const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
|
192 | const isLF = (index) => _buf[index] === CHAR_LF;
|
193 | const isPS = (index) => _buf[index] === CHAR_PS;
|
194 | const isLS = (index) => _buf[index] === CHAR_LS;
|
195 | const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
|
196 | const index = () => _index;
|
197 | const line = () => _line;
|
198 | const column = () => _column;
|
199 | const peekOffset = () => _peekOffset;
|
200 | const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
|
201 | const currentChar = () => charAt(_index);
|
202 | const currentPeek = () => charAt(_index + _peekOffset);
|
203 | function next() {
|
204 | _peekOffset = 0;
|
205 | if (isLineEnd(_index)) {
|
206 | _line++;
|
207 | _column = 0;
|
208 | }
|
209 | if (isCRLF(_index)) {
|
210 | _index++;
|
211 | }
|
212 | _index++;
|
213 | _column++;
|
214 | return _buf[_index];
|
215 | }
|
216 | function peek() {
|
217 | if (isCRLF(_index + _peekOffset)) {
|
218 | _peekOffset++;
|
219 | }
|
220 | _peekOffset++;
|
221 | return _buf[_index + _peekOffset];
|
222 | }
|
223 | function reset() {
|
224 | _index = 0;
|
225 | _line = 1;
|
226 | _column = 1;
|
227 | _peekOffset = 0;
|
228 | }
|
229 | function resetPeek(offset = 0) {
|
230 | _peekOffset = offset;
|
231 | }
|
232 | function skipToPeek() {
|
233 | const target = _index + _peekOffset;
|
234 |
|
235 | while (target !== _index) {
|
236 | next();
|
237 | }
|
238 | _peekOffset = 0;
|
239 | }
|
240 | return {
|
241 | index,
|
242 | line,
|
243 | column,
|
244 | peekOffset,
|
245 | charAt,
|
246 | currentChar,
|
247 | currentPeek,
|
248 | next,
|
249 | peek,
|
250 | reset,
|
251 | resetPeek,
|
252 | skipToPeek
|
253 | };
|
254 | }
|
255 |
|
256 | const EOF = undefined;
|
257 | const LITERAL_DELIMITER = "'";
|
258 | const ERROR_DOMAIN$1 = 'tokenizer';
|
259 | function createTokenizer(source, options = {}) {
|
260 | const location = options.location !== false;
|
261 | const _scnr = createScanner(source);
|
262 | const currentOffset = () => _scnr.index();
|
263 | const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
|
264 | const _initLoc = currentPosition();
|
265 | const _initOffset = currentOffset();
|
266 | const _context = {
|
267 | currentType: 14 ,
|
268 | offset: _initOffset,
|
269 | startLoc: _initLoc,
|
270 | endLoc: _initLoc,
|
271 | lastType: 14 ,
|
272 | lastOffset: _initOffset,
|
273 | lastStartLoc: _initLoc,
|
274 | lastEndLoc: _initLoc,
|
275 | braceNest: 0,
|
276 | inLinked: false,
|
277 | text: ''
|
278 | };
|
279 | const context = () => _context;
|
280 | const { onError } = options;
|
281 | function emitError(code, pos, offset, ...args) {
|
282 | const ctx = context();
|
283 | pos.column += offset;
|
284 | pos.offset += offset;
|
285 | if (onError) {
|
286 | const loc = createLocation(ctx.startLoc, pos);
|
287 | const err = createCompileError(code, loc, {
|
288 | domain: ERROR_DOMAIN$1,
|
289 | args
|
290 | });
|
291 | onError(err);
|
292 | }
|
293 | }
|
294 | function getToken(context, type, value) {
|
295 | context.endLoc = currentPosition();
|
296 | context.currentType = type;
|
297 | const token = { type };
|
298 | if (location) {
|
299 | token.loc = createLocation(context.startLoc, context.endLoc);
|
300 | }
|
301 | if (value != null) {
|
302 | token.value = value;
|
303 | }
|
304 | return token;
|
305 | }
|
306 | const getEndToken = (context) => getToken(context, 14 );
|
307 | function eat(scnr, ch) {
|
308 | if (scnr.currentChar() === ch) {
|
309 | scnr.next();
|
310 | return ch;
|
311 | }
|
312 | else {
|
313 | emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
|
314 | return '';
|
315 | }
|
316 | }
|
317 | function peekSpaces(scnr) {
|
318 | let buf = '';
|
319 | while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
|
320 | buf += scnr.currentPeek();
|
321 | scnr.peek();
|
322 | }
|
323 | return buf;
|
324 | }
|
325 | function skipSpaces(scnr) {
|
326 | const buf = peekSpaces(scnr);
|
327 | scnr.skipToPeek();
|
328 | return buf;
|
329 | }
|
330 | function isIdentifierStart(ch) {
|
331 | if (ch === EOF) {
|
332 | return false;
|
333 | }
|
334 | const cc = ch.charCodeAt(0);
|
335 | return ((cc >= 97 && cc <= 122) ||
|
336 | (cc >= 65 && cc <= 90) ||
|
337 | cc === 95
|
338 | );
|
339 | }
|
340 | function isNumberStart(ch) {
|
341 | if (ch === EOF) {
|
342 | return false;
|
343 | }
|
344 | const cc = ch.charCodeAt(0);
|
345 | return cc >= 48 && cc <= 57;
|
346 | }
|
347 | function isNamedIdentifierStart(scnr, context) {
|
348 | const { currentType } = context;
|
349 | if (currentType !== 2 ) {
|
350 | return false;
|
351 | }
|
352 | peekSpaces(scnr);
|
353 | const ret = isIdentifierStart(scnr.currentPeek());
|
354 | scnr.resetPeek();
|
355 | return ret;
|
356 | }
|
357 | function isListIdentifierStart(scnr, context) {
|
358 | const { currentType } = context;
|
359 | if (currentType !== 2 ) {
|
360 | return false;
|
361 | }
|
362 | peekSpaces(scnr);
|
363 | const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
|
364 | const ret = isNumberStart(ch);
|
365 | scnr.resetPeek();
|
366 | return ret;
|
367 | }
|
368 | function isLiteralStart(scnr, context) {
|
369 | const { currentType } = context;
|
370 | if (currentType !== 2 ) {
|
371 | return false;
|
372 | }
|
373 | peekSpaces(scnr);
|
374 | const ret = scnr.currentPeek() === LITERAL_DELIMITER;
|
375 | scnr.resetPeek();
|
376 | return ret;
|
377 | }
|
378 | function isLinkedDotStart(scnr, context) {
|
379 | const { currentType } = context;
|
380 | if (currentType !== 8 ) {
|
381 | return false;
|
382 | }
|
383 | peekSpaces(scnr);
|
384 | const ret = scnr.currentPeek() === "." ;
|
385 | scnr.resetPeek();
|
386 | return ret;
|
387 | }
|
388 | function isLinkedModifierStart(scnr, context) {
|
389 | const { currentType } = context;
|
390 | if (currentType !== 9 ) {
|
391 | return false;
|
392 | }
|
393 | peekSpaces(scnr);
|
394 | const ret = isIdentifierStart(scnr.currentPeek());
|
395 | scnr.resetPeek();
|
396 | return ret;
|
397 | }
|
398 | function isLinkedDelimiterStart(scnr, context) {
|
399 | const { currentType } = context;
|
400 | if (!(currentType === 8 ||
|
401 | currentType === 12 )) {
|
402 | return false;
|
403 | }
|
404 | peekSpaces(scnr);
|
405 | const ret = scnr.currentPeek() === ":" ;
|
406 | scnr.resetPeek();
|
407 | return ret;
|
408 | }
|
409 | function isLinkedReferStart(scnr, context) {
|
410 | const { currentType } = context;
|
411 | if (currentType !== 10 ) {
|
412 | return false;
|
413 | }
|
414 | const fn = () => {
|
415 | const ch = scnr.currentPeek();
|
416 | if (ch === "{" ) {
|
417 | return isIdentifierStart(scnr.peek());
|
418 | }
|
419 | else if (ch === "@" ||
|
420 | ch === "%" ||
|
421 | ch === "|" ||
|
422 | ch === ":" ||
|
423 | ch === "." ||
|
424 | ch === CHAR_SP ||
|
425 | !ch) {
|
426 | return false;
|
427 | }
|
428 | else if (ch === CHAR_LF) {
|
429 | scnr.peek();
|
430 | return fn();
|
431 | }
|
432 | else {
|
433 |
|
434 | return isIdentifierStart(ch);
|
435 | }
|
436 | };
|
437 | const ret = fn();
|
438 | scnr.resetPeek();
|
439 | return ret;
|
440 | }
|
441 | function isPluralStart(scnr) {
|
442 | peekSpaces(scnr);
|
443 | const ret = scnr.currentPeek() === "|" ;
|
444 | scnr.resetPeek();
|
445 | return ret;
|
446 | }
|
447 | function isTextStart(scnr, reset = true) {
|
448 | const fn = (hasSpace = false, prev = '', detectModulo = false) => {
|
449 | const ch = scnr.currentPeek();
|
450 | if (ch === "{" ) {
|
451 | return prev === "%" ? false : hasSpace;
|
452 | }
|
453 | else if (ch === "@" || !ch) {
|
454 | return prev === "%" ? true : hasSpace;
|
455 | }
|
456 | else if (ch === "%" ) {
|
457 | scnr.peek();
|
458 | return fn(hasSpace, "%" , true);
|
459 | }
|
460 | else if (ch === "|" ) {
|
461 | return prev === "%" || detectModulo
|
462 | ? true
|
463 | : !(prev === CHAR_SP || prev === CHAR_LF);
|
464 | }
|
465 | else if (ch === CHAR_SP) {
|
466 | scnr.peek();
|
467 | return fn(true, CHAR_SP, detectModulo);
|
468 | }
|
469 | else if (ch === CHAR_LF) {
|
470 | scnr.peek();
|
471 | return fn(true, CHAR_LF, detectModulo);
|
472 | }
|
473 | else {
|
474 | return true;
|
475 | }
|
476 | };
|
477 | const ret = fn();
|
478 | reset && scnr.resetPeek();
|
479 | return ret;
|
480 | }
|
481 | function takeChar(scnr, fn) {
|
482 | const ch = scnr.currentChar();
|
483 | if (ch === EOF) {
|
484 | return EOF;
|
485 | }
|
486 | if (fn(ch)) {
|
487 | scnr.next();
|
488 | return ch;
|
489 | }
|
490 | return null;
|
491 | }
|
492 | function takeIdentifierChar(scnr) {
|
493 | const closure = (ch) => {
|
494 | const cc = ch.charCodeAt(0);
|
495 | return ((cc >= 97 && cc <= 122) ||
|
496 | (cc >= 65 && cc <= 90) ||
|
497 | (cc >= 48 && cc <= 57) ||
|
498 | cc === 95 ||
|
499 | cc === 36
|
500 | );
|
501 | };
|
502 | return takeChar(scnr, closure);
|
503 | }
|
504 | function takeDigit(scnr) {
|
505 | const closure = (ch) => {
|
506 | const cc = ch.charCodeAt(0);
|
507 | return cc >= 48 && cc <= 57;
|
508 | };
|
509 | return takeChar(scnr, closure);
|
510 | }
|
511 | function takeHexDigit(scnr) {
|
512 | const closure = (ch) => {
|
513 | const cc = ch.charCodeAt(0);
|
514 | return ((cc >= 48 && cc <= 57) ||
|
515 | (cc >= 65 && cc <= 70) ||
|
516 | (cc >= 97 && cc <= 102));
|
517 | };
|
518 | return takeChar(scnr, closure);
|
519 | }
|
520 | function getDigits(scnr) {
|
521 | let ch = '';
|
522 | let num = '';
|
523 | while ((ch = takeDigit(scnr))) {
|
524 | num += ch;
|
525 | }
|
526 | return num;
|
527 | }
|
528 | function readText(scnr) {
|
529 | const fn = (buf) => {
|
530 | const ch = scnr.currentChar();
|
531 | if (ch === "{" ||
|
532 | ch === "}" ||
|
533 | ch === "@" ||
|
534 | !ch) {
|
535 | return buf;
|
536 | }
|
537 | else if (ch === "%" ) {
|
538 | if (isTextStart(scnr)) {
|
539 | buf += ch;
|
540 | scnr.next();
|
541 | return fn(buf);
|
542 | }
|
543 | else {
|
544 | return buf;
|
545 | }
|
546 | }
|
547 | else if (ch === "|" ) {
|
548 | return buf;
|
549 | }
|
550 | else if (ch === CHAR_SP || ch === CHAR_LF) {
|
551 | if (isTextStart(scnr)) {
|
552 | buf += ch;
|
553 | scnr.next();
|
554 | return fn(buf);
|
555 | }
|
556 | else if (isPluralStart(scnr)) {
|
557 | return buf;
|
558 | }
|
559 | else {
|
560 | buf += ch;
|
561 | scnr.next();
|
562 | return fn(buf);
|
563 | }
|
564 | }
|
565 | else {
|
566 | buf += ch;
|
567 | scnr.next();
|
568 | return fn(buf);
|
569 | }
|
570 | };
|
571 | return fn('');
|
572 | }
|
573 | function readNamedIdentifier(scnr) {
|
574 | skipSpaces(scnr);
|
575 | let ch = '';
|
576 | let name = '';
|
577 | while ((ch = takeIdentifierChar(scnr))) {
|
578 | name += ch;
|
579 | }
|
580 | if (scnr.currentChar() === EOF) {
|
581 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
582 | }
|
583 | return name;
|
584 | }
|
585 | function readListIdentifier(scnr) {
|
586 | skipSpaces(scnr);
|
587 | let value = '';
|
588 | if (scnr.currentChar() === '-') {
|
589 | scnr.next();
|
590 | value += `-${getDigits(scnr)}`;
|
591 | }
|
592 | else {
|
593 | value += getDigits(scnr);
|
594 | }
|
595 | if (scnr.currentChar() === EOF) {
|
596 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
597 | }
|
598 | return value;
|
599 | }
|
600 | function readLiteral(scnr) {
|
601 | skipSpaces(scnr);
|
602 | eat(scnr, `\'`);
|
603 | let ch = '';
|
604 | let literal = '';
|
605 | const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
|
606 | while ((ch = takeChar(scnr, fn))) {
|
607 | if (ch === '\\') {
|
608 | literal += readEscapeSequence(scnr);
|
609 | }
|
610 | else {
|
611 | literal += ch;
|
612 | }
|
613 | }
|
614 | const current = scnr.currentChar();
|
615 | if (current === CHAR_LF || current === EOF) {
|
616 | emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
|
617 |
|
618 | if (current === CHAR_LF) {
|
619 | scnr.next();
|
620 | eat(scnr, `\'`);
|
621 | }
|
622 | return literal;
|
623 | }
|
624 | eat(scnr, `\'`);
|
625 | return literal;
|
626 | }
|
627 | function readEscapeSequence(scnr) {
|
628 | const ch = scnr.currentChar();
|
629 | switch (ch) {
|
630 | case '\\':
|
631 | case `\'`:
|
632 | scnr.next();
|
633 | return `\\${ch}`;
|
634 | case 'u':
|
635 | return readUnicodeEscapeSequence(scnr, ch, 4);
|
636 | case 'U':
|
637 | return readUnicodeEscapeSequence(scnr, ch, 6);
|
638 | default:
|
639 | emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
|
640 | return '';
|
641 | }
|
642 | }
|
643 | function readUnicodeEscapeSequence(scnr, unicode, digits) {
|
644 | eat(scnr, unicode);
|
645 | let sequence = '';
|
646 | for (let i = 0; i < digits; i++) {
|
647 | const ch = takeHexDigit(scnr);
|
648 | if (!ch) {
|
649 | emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
|
650 | break;
|
651 | }
|
652 | sequence += ch;
|
653 | }
|
654 | return `\\${unicode}${sequence}`;
|
655 | }
|
656 | function readInvalidIdentifier(scnr) {
|
657 | skipSpaces(scnr);
|
658 | let ch = '';
|
659 | let identifiers = '';
|
660 | const closure = (ch) => ch !== "{" &&
|
661 | ch !== "}" &&
|
662 | ch !== CHAR_SP &&
|
663 | ch !== CHAR_LF;
|
664 | while ((ch = takeChar(scnr, closure))) {
|
665 | identifiers += ch;
|
666 | }
|
667 | return identifiers;
|
668 | }
|
669 | function readLinkedModifier(scnr) {
|
670 | let ch = '';
|
671 | let name = '';
|
672 | while ((ch = takeIdentifierChar(scnr))) {
|
673 | name += ch;
|
674 | }
|
675 | return name;
|
676 | }
|
677 | function readLinkedRefer(scnr) {
|
678 | const fn = (detect = false, buf) => {
|
679 | const ch = scnr.currentChar();
|
680 | if (ch === "{" ||
|
681 | ch === "%" ||
|
682 | ch === "@" ||
|
683 | ch === "|" ||
|
684 | !ch) {
|
685 | return buf;
|
686 | }
|
687 | else if (ch === CHAR_SP) {
|
688 | return buf;
|
689 | }
|
690 | else if (ch === CHAR_LF) {
|
691 | buf += ch;
|
692 | scnr.next();
|
693 | return fn(detect, buf);
|
694 | }
|
695 | else {
|
696 | buf += ch;
|
697 | scnr.next();
|
698 | return fn(true, buf);
|
699 | }
|
700 | };
|
701 | return fn(false, '');
|
702 | }
|
703 | function readPlural(scnr) {
|
704 | skipSpaces(scnr);
|
705 | const plural = eat(scnr, "|" );
|
706 | skipSpaces(scnr);
|
707 | return plural;
|
708 | }
|
709 |
|
710 | function readTokenInPlaceholder(scnr, context) {
|
711 | let token = null;
|
712 | const ch = scnr.currentChar();
|
713 | switch (ch) {
|
714 | case "{" :
|
715 | if (context.braceNest >= 1) {
|
716 | emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
|
717 | }
|
718 | scnr.next();
|
719 | token = getToken(context, 2 , "{" );
|
720 | skipSpaces(scnr);
|
721 | context.braceNest++;
|
722 | return token;
|
723 | case "}" :
|
724 | if (context.braceNest > 0 &&
|
725 | context.currentType === 2 ) {
|
726 | emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
|
727 | }
|
728 | scnr.next();
|
729 | token = getToken(context, 3 , "}" );
|
730 | context.braceNest--;
|
731 | context.braceNest > 0 && skipSpaces(scnr);
|
732 | if (context.inLinked && context.braceNest === 0) {
|
733 | context.inLinked = false;
|
734 | }
|
735 | return token;
|
736 | case "@" :
|
737 | if (context.braceNest > 0) {
|
738 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
739 | }
|
740 | token = readTokenInLinked(scnr, context) || getEndToken(context);
|
741 | context.braceNest = 0;
|
742 | return token;
|
743 | default:
|
744 | let validNamedIdentifier = true;
|
745 | let validListIdentifier = true;
|
746 | let validLiteral = true;
|
747 | if (isPluralStart(scnr)) {
|
748 | if (context.braceNest > 0) {
|
749 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
750 | }
|
751 | token = getToken(context, 1 , readPlural(scnr));
|
752 |
|
753 | context.braceNest = 0;
|
754 | context.inLinked = false;
|
755 | return token;
|
756 | }
|
757 | if (context.braceNest > 0 &&
|
758 | (context.currentType === 5 ||
|
759 | context.currentType === 6 ||
|
760 | context.currentType === 7 )) {
|
761 | emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
|
762 | context.braceNest = 0;
|
763 | return readToken(scnr, context);
|
764 | }
|
765 | if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
|
766 | token = getToken(context, 5 , readNamedIdentifier(scnr));
|
767 | skipSpaces(scnr);
|
768 | return token;
|
769 | }
|
770 | if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
|
771 | token = getToken(context, 6 , readListIdentifier(scnr));
|
772 | skipSpaces(scnr);
|
773 | return token;
|
774 | }
|
775 | if ((validLiteral = isLiteralStart(scnr, context))) {
|
776 | token = getToken(context, 7 , readLiteral(scnr));
|
777 | skipSpaces(scnr);
|
778 | return token;
|
779 | }
|
780 | if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
|
781 |
|
782 | token = getToken(context, 13 , readInvalidIdentifier(scnr));
|
783 | emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
|
784 | skipSpaces(scnr);
|
785 | return token;
|
786 | }
|
787 | break;
|
788 | }
|
789 | return token;
|
790 | }
|
791 |
|
792 | function readTokenInLinked(scnr, context) {
|
793 | const { currentType } = context;
|
794 | let token = null;
|
795 | const ch = scnr.currentChar();
|
796 | if ((currentType === 8 ||
|
797 | currentType === 9 ||
|
798 | currentType === 12 ||
|
799 | currentType === 10 ) &&
|
800 | (ch === CHAR_LF || ch === CHAR_SP)) {
|
801 | emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
|
802 | }
|
803 | switch (ch) {
|
804 | case "@" :
|
805 | scnr.next();
|
806 | token = getToken(context, 8 , "@" );
|
807 | context.inLinked = true;
|
808 | return token;
|
809 | case "." :
|
810 | skipSpaces(scnr);
|
811 | scnr.next();
|
812 | return getToken(context, 9 , "." );
|
813 | case ":" :
|
814 | skipSpaces(scnr);
|
815 | scnr.next();
|
816 | return getToken(context, 10 , ":" );
|
817 | default:
|
818 | if (isPluralStart(scnr)) {
|
819 | token = getToken(context, 1 , readPlural(scnr));
|
820 |
|
821 | context.braceNest = 0;
|
822 | context.inLinked = false;
|
823 | return token;
|
824 | }
|
825 | if (isLinkedDotStart(scnr, context) ||
|
826 | isLinkedDelimiterStart(scnr, context)) {
|
827 | skipSpaces(scnr);
|
828 | return readTokenInLinked(scnr, context);
|
829 | }
|
830 | if (isLinkedModifierStart(scnr, context)) {
|
831 | skipSpaces(scnr);
|
832 | return getToken(context, 12 , readLinkedModifier(scnr));
|
833 | }
|
834 | if (isLinkedReferStart(scnr, context)) {
|
835 | skipSpaces(scnr);
|
836 | if (ch === "{" ) {
|
837 |
|
838 | return readTokenInPlaceholder(scnr, context) || token;
|
839 | }
|
840 | else {
|
841 | return getToken(context, 11 , readLinkedRefer(scnr));
|
842 | }
|
843 | }
|
844 | if (currentType === 8 ) {
|
845 | emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
|
846 | }
|
847 | context.braceNest = 0;
|
848 | context.inLinked = false;
|
849 | return readToken(scnr, context);
|
850 | }
|
851 | }
|
852 |
|
853 | function readToken(scnr, context) {
|
854 | let token = { type: 14 };
|
855 | if (context.braceNest > 0) {
|
856 | return readTokenInPlaceholder(scnr, context) || getEndToken(context);
|
857 | }
|
858 | if (context.inLinked) {
|
859 | return readTokenInLinked(scnr, context) || getEndToken(context);
|
860 | }
|
861 | const ch = scnr.currentChar();
|
862 | switch (ch) {
|
863 | case "{" :
|
864 | return readTokenInPlaceholder(scnr, context) || getEndToken(context);
|
865 | case "}" :
|
866 | emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
|
867 | scnr.next();
|
868 | return getToken(context, 3 , "}" );
|
869 | case "@" :
|
870 | return readTokenInLinked(scnr, context) || getEndToken(context);
|
871 | default:
|
872 | if (isPluralStart(scnr)) {
|
873 | token = getToken(context, 1 , readPlural(scnr));
|
874 |
|
875 | context.braceNest = 0;
|
876 | context.inLinked = false;
|
877 | return token;
|
878 | }
|
879 | if (isTextStart(scnr)) {
|
880 | return getToken(context, 0 , readText(scnr));
|
881 | }
|
882 | if (ch === "%" ) {
|
883 | scnr.next();
|
884 | return getToken(context, 4 , "%" );
|
885 | }
|
886 | break;
|
887 | }
|
888 | return token;
|
889 | }
|
890 | function nextToken() {
|
891 | const { currentType, offset, startLoc, endLoc } = _context;
|
892 | _context.lastType = currentType;
|
893 | _context.lastOffset = offset;
|
894 | _context.lastStartLoc = startLoc;
|
895 | _context.lastEndLoc = endLoc;
|
896 | _context.offset = currentOffset();
|
897 | _context.startLoc = currentPosition();
|
898 | if (_scnr.currentChar() === EOF) {
|
899 | return getToken(_context, 14 );
|
900 | }
|
901 | return readToken(_scnr, _context);
|
902 | }
|
903 | return {
|
904 | nextToken,
|
905 | currentOffset,
|
906 | currentPosition,
|
907 | context
|
908 | };
|
909 | }
|
910 |
|
911 | const ERROR_DOMAIN = 'parser';
|
912 |
|
913 | const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
|
914 | function fromEscapeSequence(match, codePoint4, codePoint6) {
|
915 | switch (match) {
|
916 | case `\\\\`:
|
917 | return `\\`;
|
918 | case `\\\'`:
|
919 | return `\'`;
|
920 | default: {
|
921 | const codePoint = parseInt(codePoint4 || codePoint6, 16);
|
922 | if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
|
923 | return String.fromCodePoint(codePoint);
|
924 | }
|
925 |
|
926 |
|
927 | return '�';
|
928 | }
|
929 | }
|
930 | }
|
931 | function createParser(options = {}) {
|
932 | const location = options.location !== false;
|
933 | const { onError } = options;
|
934 | function emitError(tokenzer, code, start, offset, ...args) {
|
935 | const end = tokenzer.currentPosition();
|
936 | end.offset += offset;
|
937 | end.column += offset;
|
938 | if (onError) {
|
939 | const loc = createLocation(start, end);
|
940 | const err = createCompileError(code, loc, {
|
941 | domain: ERROR_DOMAIN,
|
942 | args
|
943 | });
|
944 | onError(err);
|
945 | }
|
946 | }
|
947 | function startNode(type, offset, loc) {
|
948 | const node = {
|
949 | type,
|
950 | start: offset,
|
951 | end: offset
|
952 | };
|
953 | if (location) {
|
954 | node.loc = { start: loc, end: loc };
|
955 | }
|
956 | return node;
|
957 | }
|
958 | function endNode(node, offset, pos, type) {
|
959 | node.end = offset;
|
960 | if (type) {
|
961 | node.type = type;
|
962 | }
|
963 | if (location && node.loc) {
|
964 | node.loc.end = pos;
|
965 | }
|
966 | }
|
967 | function parseText(tokenizer, value) {
|
968 | const context = tokenizer.context();
|
969 | const node = startNode(3 , context.offset, context.startLoc);
|
970 | node.value = value;
|
971 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
972 | return node;
|
973 | }
|
974 | function parseList(tokenizer, index) {
|
975 | const context = tokenizer.context();
|
976 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
977 | const node = startNode(5 , offset, loc);
|
978 | node.index = parseInt(index, 10);
|
979 | tokenizer.nextToken();
|
980 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
981 | return node;
|
982 | }
|
983 | function parseNamed(tokenizer, key) {
|
984 | const context = tokenizer.context();
|
985 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
986 | const node = startNode(4 , offset, loc);
|
987 | node.key = key;
|
988 | tokenizer.nextToken();
|
989 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
990 | return node;
|
991 | }
|
992 | function parseLiteral(tokenizer, value) {
|
993 | const context = tokenizer.context();
|
994 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
995 | const node = startNode(9 , offset, loc);
|
996 | node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
|
997 | tokenizer.nextToken();
|
998 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
999 | return node;
|
1000 | }
|
1001 | function parseLinkedModifier(tokenizer) {
|
1002 | const token = tokenizer.nextToken();
|
1003 | const context = tokenizer.context();
|
1004 | const { lastOffset: offset, lastStartLoc: loc } = context;
|
1005 | const node = startNode(8 , offset, loc);
|
1006 | if (token.type !== 12 ) {
|
1007 |
|
1008 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
|
1009 | node.value = '';
|
1010 | endNode(node, offset, loc);
|
1011 | return {
|
1012 | nextConsumeToken: token,
|
1013 | node
|
1014 | };
|
1015 | }
|
1016 |
|
1017 | if (token.value == null) {
|
1018 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1019 | }
|
1020 | node.value = token.value || '';
|
1021 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1022 | return {
|
1023 | node
|
1024 | };
|
1025 | }
|
1026 | function parseLinkedKey(tokenizer, value) {
|
1027 | const context = tokenizer.context();
|
1028 | const node = startNode(7 , context.offset, context.startLoc);
|
1029 | node.value = value;
|
1030 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1031 | return node;
|
1032 | }
|
1033 | function parseLinked(tokenizer) {
|
1034 | const context = tokenizer.context();
|
1035 | const linkedNode = startNode(6 , context.offset, context.startLoc);
|
1036 | let token = tokenizer.nextToken();
|
1037 | if (token.type === 9 ) {
|
1038 | const parsed = parseLinkedModifier(tokenizer);
|
1039 | linkedNode.modifier = parsed.node;
|
1040 | token = parsed.nextConsumeToken || tokenizer.nextToken();
|
1041 | }
|
1042 |
|
1043 | if (token.type !== 10 ) {
|
1044 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1045 | }
|
1046 | token = tokenizer.nextToken();
|
1047 |
|
1048 | if (token.type === 2 ) {
|
1049 | token = tokenizer.nextToken();
|
1050 | }
|
1051 | switch (token.type) {
|
1052 | case 11 :
|
1053 | if (token.value == null) {
|
1054 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1055 | }
|
1056 | linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
|
1057 | break;
|
1058 | case 5 :
|
1059 | if (token.value == null) {
|
1060 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1061 | }
|
1062 | linkedNode.key = parseNamed(tokenizer, token.value || '');
|
1063 | break;
|
1064 | case 6 :
|
1065 | if (token.value == null) {
|
1066 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1067 | }
|
1068 | linkedNode.key = parseList(tokenizer, token.value || '');
|
1069 | break;
|
1070 | case 7 :
|
1071 | if (token.value == null) {
|
1072 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1073 | }
|
1074 | linkedNode.key = parseLiteral(tokenizer, token.value || '');
|
1075 | break;
|
1076 | default:
|
1077 |
|
1078 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
|
1079 | const nextContext = tokenizer.context();
|
1080 | const emptyLinkedKeyNode = startNode(7 , nextContext.offset, nextContext.startLoc);
|
1081 | emptyLinkedKeyNode.value = '';
|
1082 | endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
|
1083 | linkedNode.key = emptyLinkedKeyNode;
|
1084 | endNode(linkedNode, nextContext.offset, nextContext.startLoc);
|
1085 | return {
|
1086 | nextConsumeToken: token,
|
1087 | node: linkedNode
|
1088 | };
|
1089 | }
|
1090 | endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1091 | return {
|
1092 | node: linkedNode
|
1093 | };
|
1094 | }
|
1095 | function parseMessage(tokenizer) {
|
1096 | const context = tokenizer.context();
|
1097 | const startOffset = context.currentType === 1
|
1098 | ? tokenizer.currentOffset()
|
1099 | : context.offset;
|
1100 | const startLoc = context.currentType === 1
|
1101 | ? context.endLoc
|
1102 | : context.startLoc;
|
1103 | const node = startNode(2 , startOffset, startLoc);
|
1104 | node.items = [];
|
1105 | let nextToken = null;
|
1106 | do {
|
1107 | const token = nextToken || tokenizer.nextToken();
|
1108 | nextToken = null;
|
1109 | switch (token.type) {
|
1110 | case 0 :
|
1111 | if (token.value == null) {
|
1112 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1113 | }
|
1114 | node.items.push(parseText(tokenizer, token.value || ''));
|
1115 | break;
|
1116 | case 6 :
|
1117 | if (token.value == null) {
|
1118 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1119 | }
|
1120 | node.items.push(parseList(tokenizer, token.value || ''));
|
1121 | break;
|
1122 | case 5 :
|
1123 | if (token.value == null) {
|
1124 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1125 | }
|
1126 | node.items.push(parseNamed(tokenizer, token.value || ''));
|
1127 | break;
|
1128 | case 7 :
|
1129 | if (token.value == null) {
|
1130 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
|
1131 | }
|
1132 | node.items.push(parseLiteral(tokenizer, token.value || ''));
|
1133 | break;
|
1134 | case 8 :
|
1135 | const parsed = parseLinked(tokenizer);
|
1136 | node.items.push(parsed.node);
|
1137 | nextToken = parsed.nextConsumeToken || null;
|
1138 | break;
|
1139 | }
|
1140 | } while (context.currentType !== 14 &&
|
1141 | context.currentType !== 1 );
|
1142 |
|
1143 | const endOffset = context.currentType === 1
|
1144 | ? context.lastOffset
|
1145 | : tokenizer.currentOffset();
|
1146 | const endLoc = context.currentType === 1
|
1147 | ? context.lastEndLoc
|
1148 | : tokenizer.currentPosition();
|
1149 | endNode(node, endOffset, endLoc);
|
1150 | return node;
|
1151 | }
|
1152 | function parsePlural(tokenizer, offset, loc, msgNode) {
|
1153 | const context = tokenizer.context();
|
1154 | let hasEmptyMessage = msgNode.items.length === 0;
|
1155 | const node = startNode(1 , offset, loc);
|
1156 | node.cases = [];
|
1157 | node.cases.push(msgNode);
|
1158 | do {
|
1159 | const msg = parseMessage(tokenizer);
|
1160 | if (!hasEmptyMessage) {
|
1161 | hasEmptyMessage = msg.items.length === 0;
|
1162 | }
|
1163 | node.cases.push(msg);
|
1164 | } while (context.currentType !== 14 );
|
1165 | if (hasEmptyMessage) {
|
1166 | emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
|
1167 | }
|
1168 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1169 | return node;
|
1170 | }
|
1171 | function parseResource(tokenizer) {
|
1172 | const context = tokenizer.context();
|
1173 | const { offset, startLoc } = context;
|
1174 | const msgNode = parseMessage(tokenizer);
|
1175 | if (context.currentType === 14 ) {
|
1176 | return msgNode;
|
1177 | }
|
1178 | else {
|
1179 | return parsePlural(tokenizer, offset, startLoc, msgNode);
|
1180 | }
|
1181 | }
|
1182 | function parse(source) {
|
1183 | const tokenizer = createTokenizer(source, assign({}, options));
|
1184 | const context = tokenizer.context();
|
1185 | const node = startNode(0 , context.offset, context.startLoc);
|
1186 | if (location && node.loc) {
|
1187 | node.loc.source = source;
|
1188 | }
|
1189 | node.body = parseResource(tokenizer);
|
1190 |
|
1191 | if (context.currentType !== 14 ) {
|
1192 | emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
|
1193 | }
|
1194 | endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
|
1195 | return node;
|
1196 | }
|
1197 | return { parse };
|
1198 | }
|
1199 | function getTokenCaption(token) {
|
1200 | if (token.type === 14 ) {
|
1201 | return 'EOF';
|
1202 | }
|
1203 | const name = (token.value || '').replace(/\r?\n/gu, '\\n');
|
1204 | return name.length > 10 ? name.slice(0, 9) + '…' : name;
|
1205 | }
|
1206 |
|
1207 | function createTransformer(ast, options = {} // eslint-disable-line
|
1208 | ) {
|
1209 | const _context = {
|
1210 | ast,
|
1211 | helpers: new Set()
|
1212 | };
|
1213 | const context = () => _context;
|
1214 | const helper = (name) => {
|
1215 | _context.helpers.add(name);
|
1216 | return name;
|
1217 | };
|
1218 | return { context, helper };
|
1219 | }
|
1220 | function traverseNodes(nodes, transformer) {
|
1221 | for (let i = 0; i < nodes.length; i++) {
|
1222 | traverseNode(nodes[i], transformer);
|
1223 | }
|
1224 | }
|
1225 | function traverseNode(node, transformer) {
|
1226 |
|
1227 | switch (node.type) {
|
1228 | case 1 :
|
1229 | traverseNodes(node.cases, transformer);
|
1230 | transformer.helper("plural" );
|
1231 | break;
|
1232 | case 2 :
|
1233 | traverseNodes(node.items, transformer);
|
1234 | break;
|
1235 | case 6 :
|
1236 | const linked = node;
|
1237 | traverseNode(linked.key, transformer);
|
1238 | transformer.helper("linked" );
|
1239 | break;
|
1240 | case 5 :
|
1241 | transformer.helper("interpolate" );
|
1242 | transformer.helper("list" );
|
1243 | break;
|
1244 | case 4 :
|
1245 | transformer.helper("interpolate" );
|
1246 | transformer.helper("named" );
|
1247 | break;
|
1248 | }
|
1249 |
|
1250 | }
|
1251 |
|
1252 | function transform(ast, options = {} // eslint-disable-line
|
1253 | ) {
|
1254 | const transformer = createTransformer(ast);
|
1255 | transformer.helper("normalize" );
|
1256 |
|
1257 | ast.body && traverseNode(ast.body, transformer);
|
1258 |
|
1259 | const context = transformer.context();
|
1260 | ast.helpers = Array.from(context.helpers);
|
1261 | }
|
1262 |
|
1263 | function createCodeGenerator(ast, options) {
|
1264 | const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
|
1265 | const _context = {
|
1266 | source: ast.loc.source,
|
1267 | filename,
|
1268 | code: '',
|
1269 | column: 1,
|
1270 | line: 1,
|
1271 | offset: 0,
|
1272 | map: undefined,
|
1273 | breakLineCode,
|
1274 | needIndent: _needIndent,
|
1275 | indentLevel: 0
|
1276 | };
|
1277 | const context = () => _context;
|
1278 | function push(code, node) {
|
1279 | _context.code += code;
|
1280 | }
|
1281 | function _newline(n, withBreakLine = true) {
|
1282 | const _breakLineCode = withBreakLine ? breakLineCode : '';
|
1283 | push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
|
1284 | }
|
1285 | function indent(withNewLine = true) {
|
1286 | const level = ++_context.indentLevel;
|
1287 | withNewLine && _newline(level);
|
1288 | }
|
1289 | function deindent(withNewLine = true) {
|
1290 | const level = --_context.indentLevel;
|
1291 | withNewLine && _newline(level);
|
1292 | }
|
1293 | function newline() {
|
1294 | _newline(_context.indentLevel);
|
1295 | }
|
1296 | const helper = (key) => `_${key}`;
|
1297 | const needIndent = () => _context.needIndent;
|
1298 | return {
|
1299 | context,
|
1300 | push,
|
1301 | indent,
|
1302 | deindent,
|
1303 | newline,
|
1304 | helper,
|
1305 | needIndent
|
1306 | };
|
1307 | }
|
1308 | function generateLinkedNode(generator, node) {
|
1309 | const { helper } = generator;
|
1310 | generator.push(`${helper("linked" /* LINKED */)}(`);
|
1311 | generateNode(generator, node.key);
|
1312 | if (node.modifier) {
|
1313 | generator.push(`, `);
|
1314 | generateNode(generator, node.modifier);
|
1315 | }
|
1316 | generator.push(`)`);
|
1317 | }
|
1318 | function generateMessageNode(generator, node) {
|
1319 | const { helper, needIndent } = generator;
|
1320 | generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
|
1321 | generator.indent(needIndent());
|
1322 | const length = node.items.length;
|
1323 | for (let i = 0; i < length; i++) {
|
1324 | generateNode(generator, node.items[i]);
|
1325 | if (i === length - 1) {
|
1326 | break;
|
1327 | }
|
1328 | generator.push(', ');
|
1329 | }
|
1330 | generator.deindent(needIndent());
|
1331 | generator.push('])');
|
1332 | }
|
1333 | function generatePluralNode(generator, node) {
|
1334 | const { helper, needIndent } = generator;
|
1335 | if (node.cases.length > 1) {
|
1336 | generator.push(`${helper("plural" /* PLURAL */)}([`);
|
1337 | generator.indent(needIndent());
|
1338 | const length = node.cases.length;
|
1339 | for (let i = 0; i < length; i++) {
|
1340 | generateNode(generator, node.cases[i]);
|
1341 | if (i === length - 1) {
|
1342 | break;
|
1343 | }
|
1344 | generator.push(', ');
|
1345 | }
|
1346 | generator.deindent(needIndent());
|
1347 | generator.push(`])`);
|
1348 | }
|
1349 | }
|
1350 | function generateResource(generator, node) {
|
1351 | if (node.body) {
|
1352 | generateNode(generator, node.body);
|
1353 | }
|
1354 | else {
|
1355 | generator.push('null');
|
1356 | }
|
1357 | }
|
1358 | function generateNode(generator, node) {
|
1359 | const { helper } = generator;
|
1360 | switch (node.type) {
|
1361 | case 0 :
|
1362 | generateResource(generator, node);
|
1363 | break;
|
1364 | case 1 :
|
1365 | generatePluralNode(generator, node);
|
1366 | break;
|
1367 | case 2 :
|
1368 | generateMessageNode(generator, node);
|
1369 | break;
|
1370 | case 6 :
|
1371 | generateLinkedNode(generator, node);
|
1372 | break;
|
1373 | case 8 :
|
1374 | generator.push(JSON.stringify(node.value), node);
|
1375 | break;
|
1376 | case 7 :
|
1377 | generator.push(JSON.stringify(node.value), node);
|
1378 | break;
|
1379 | case 5 :
|
1380 | generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
|
1381 | break;
|
1382 | case 4 :
|
1383 | generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
|
1384 | break;
|
1385 | case 9 :
|
1386 | generator.push(JSON.stringify(node.value), node);
|
1387 | break;
|
1388 | case 3 :
|
1389 | generator.push(JSON.stringify(node.value), node);
|
1390 | break;
|
1391 | default:
|
1392 | {
|
1393 | throw new Error(`unhandled codegen node type: ${node.type}`);
|
1394 | }
|
1395 | }
|
1396 | }
|
1397 |
|
1398 | const generate = (ast, options = {}
|
1399 | ) => {
|
1400 | const mode = isString(options.mode) ? options.mode : 'normal';
|
1401 | const filename = isString(options.filename)
|
1402 | ? options.filename
|
1403 | : 'message.intl';
|
1404 | const sourceMap = !!options.sourceMap;
|
1405 |
|
1406 | const breakLineCode = options.breakLineCode != null
|
1407 | ? options.breakLineCode
|
1408 | : mode === 'arrow'
|
1409 | ? ';'
|
1410 | : '\n';
|
1411 | const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
|
1412 | const helpers = ast.helpers || [];
|
1413 | const generator = createCodeGenerator(ast, {
|
1414 | mode,
|
1415 | filename,
|
1416 | sourceMap,
|
1417 | breakLineCode,
|
1418 | needIndent
|
1419 | });
|
1420 | generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
|
1421 | generator.indent(needIndent);
|
1422 | if (helpers.length > 0) {
|
1423 | generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
|
1424 | generator.newline();
|
1425 | }
|
1426 | generator.push(`return `);
|
1427 | generateNode(generator, ast);
|
1428 | generator.deindent(needIndent);
|
1429 | generator.push(`}`);
|
1430 | const { code, map } = generator.context();
|
1431 | return {
|
1432 | ast,
|
1433 | code,
|
1434 | map: map ? map.toJSON() : undefined
|
1435 | };
|
1436 | };
|
1437 |
|
1438 | function baseCompile(source, options = {}) {
|
1439 | const assignedOptions = assign({}, options);
|
1440 |
|
1441 | const parser = createParser(assignedOptions);
|
1442 | const ast = parser.parse(source);
|
1443 |
|
1444 | transform(ast, assignedOptions);
|
1445 |
|
1446 | return generate(ast, assignedOptions);
|
1447 | }
|
1448 |
|
1449 | const pathStateMachine = [];
|
1450 | pathStateMachine[0 ] = {
|
1451 | ["w" ]: [0 ],
|
1452 | ["i" ]: [3 , 0 ],
|
1453 | ["[" ]: [4 ],
|
1454 | ["o" ]: [7 ]
|
1455 | };
|
1456 | pathStateMachine[1 ] = {
|
1457 | ["w" ]: [1 ],
|
1458 | ["." ]: [2 ],
|
1459 | ["[" ]: [4 ],
|
1460 | ["o" ]: [7 ]
|
1461 | };
|
1462 | pathStateMachine[2 ] = {
|
1463 | ["w" ]: [2 ],
|
1464 | ["i" ]: [3 , 0 ],
|
1465 | ["0" ]: [3 , 0 ]
|
1466 | };
|
1467 | pathStateMachine[3 ] = {
|
1468 | ["i" ]: [3 , 0 ],
|
1469 | ["0" ]: [3 , 0 ],
|
1470 | ["w" ]: [1 , 1 ],
|
1471 | ["." ]: [2 , 1 ],
|
1472 | ["[" ]: [4 , 1 ],
|
1473 | ["o" ]: [7 , 1 ]
|
1474 | };
|
1475 | pathStateMachine[4 ] = {
|
1476 | ["'" ]: [5 , 0 ],
|
1477 | ["\"" ]: [6 , 0 ],
|
1478 | ["[" ]: [
|
1479 | 4 ,
|
1480 | 2
|
1481 | ],
|
1482 | ["]" ]: [1 , 3 ],
|
1483 | ["o" ]: 8 ,
|
1484 | ["l" ]: [4 , 0 ]
|
1485 | };
|
1486 | pathStateMachine[5 ] = {
|
1487 | ["'" ]: [4 , 0 ],
|
1488 | ["o" ]: 8 ,
|
1489 | ["l" ]: [5 , 0 ]
|
1490 | };
|
1491 | pathStateMachine[6 ] = {
|
1492 | ["\"" ]: [4 , 0 ],
|
1493 | ["o" ]: 8 ,
|
1494 | ["l" ]: [6 , 0 ]
|
1495 | };
|
1496 | |
1497 |
|
1498 |
|
1499 | const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
|
1500 | function isLiteral(exp) {
|
1501 | return literalValueRE.test(exp);
|
1502 | }
|
1503 | |
1504 |
|
1505 |
|
1506 | function stripQuotes(str) {
|
1507 | const a = str.charCodeAt(0);
|
1508 | const b = str.charCodeAt(str.length - 1);
|
1509 | return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
|
1510 | }
|
1511 | |
1512 |
|
1513 |
|
1514 | function getPathCharType(ch) {
|
1515 | if (ch === undefined || ch === null) {
|
1516 | return "o" ;
|
1517 | }
|
1518 | const code = ch.charCodeAt(0);
|
1519 | switch (code) {
|
1520 | case 0x5b:
|
1521 | case 0x5d:
|
1522 | case 0x2e:
|
1523 | case 0x22:
|
1524 | case 0x27:
|
1525 | return ch;
|
1526 | case 0x5f:
|
1527 | case 0x24:
|
1528 | case 0x2d:
|
1529 | return "i" ;
|
1530 | case 0x09:
|
1531 | case 0x0a:
|
1532 | case 0x0d:
|
1533 | case 0xa0:
|
1534 | case 0xfeff:
|
1535 | case 0x2028:
|
1536 | case 0x2029:
|
1537 | return "w" ;
|
1538 | }
|
1539 | return "i" ;
|
1540 | }
|
1541 | |
1542 |
|
1543 |
|
1544 |
|
1545 |
|
1546 | function formatSubPath(path) {
|
1547 | const trimmed = path.trim();
|
1548 |
|
1549 | if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
|
1550 | return false;
|
1551 | }
|
1552 | return isLiteral(trimmed)
|
1553 | ? stripQuotes(trimmed)
|
1554 | : "*" + trimmed;
|
1555 | }
|
1556 | |
1557 |
|
1558 |
|
1559 | function parse(path) {
|
1560 | const keys = [];
|
1561 | let index = -1;
|
1562 | let mode = 0 ;
|
1563 | let subPathDepth = 0;
|
1564 | let c;
|
1565 | let key;
|
1566 | let newChar;
|
1567 | let type;
|
1568 | let transition;
|
1569 | let action;
|
1570 | let typeMap;
|
1571 | const actions = [];
|
1572 | actions[0 ] = () => {
|
1573 | if (key === undefined) {
|
1574 | key = newChar;
|
1575 | }
|
1576 | else {
|
1577 | key += newChar;
|
1578 | }
|
1579 | };
|
1580 | actions[1 ] = () => {
|
1581 | if (key !== undefined) {
|
1582 | keys.push(key);
|
1583 | key = undefined;
|
1584 | }
|
1585 | };
|
1586 | actions[2 ] = () => {
|
1587 | actions[0 ]();
|
1588 | subPathDepth++;
|
1589 | };
|
1590 | actions[3 ] = () => {
|
1591 | if (subPathDepth > 0) {
|
1592 | subPathDepth--;
|
1593 | mode = 4 ;
|
1594 | actions[0 ]();
|
1595 | }
|
1596 | else {
|
1597 | subPathDepth = 0;
|
1598 | if (key === undefined) {
|
1599 | return false;
|
1600 | }
|
1601 | key = formatSubPath(key);
|
1602 | if (key === false) {
|
1603 | return false;
|
1604 | }
|
1605 | else {
|
1606 | actions[1 ]();
|
1607 | }
|
1608 | }
|
1609 | };
|
1610 | function maybeUnescapeQuote() {
|
1611 | const nextChar = path[index + 1];
|
1612 | if ((mode === 5 &&
|
1613 | nextChar === "'" ) ||
|
1614 | (mode === 6 &&
|
1615 | nextChar === "\"" )) {
|
1616 | index++;
|
1617 | newChar = '\\' + nextChar;
|
1618 | actions[0 ]();
|
1619 | return true;
|
1620 | }
|
1621 | }
|
1622 | while (mode !== null) {
|
1623 | index++;
|
1624 | c = path[index];
|
1625 | if (c === '\\' && maybeUnescapeQuote()) {
|
1626 | continue;
|
1627 | }
|
1628 | type = getPathCharType(c);
|
1629 | typeMap = pathStateMachine[mode];
|
1630 | transition = typeMap[type] || typeMap["l" ] || 8 ;
|
1631 |
|
1632 | if (transition === 8 ) {
|
1633 | return;
|
1634 | }
|
1635 | mode = transition[0];
|
1636 | if (transition[1] !== undefined) {
|
1637 | action = actions[transition[1]];
|
1638 | if (action) {
|
1639 | newChar = c;
|
1640 | if (action() === false) {
|
1641 | return;
|
1642 | }
|
1643 | }
|
1644 | }
|
1645 |
|
1646 | if (mode === 7 ) {
|
1647 | return keys;
|
1648 | }
|
1649 | }
|
1650 | }
|
1651 |
|
1652 | const cache = new Map();
|
1653 | |
1654 |
|
1655 |
|
1656 |
|
1657 |
|
1658 |
|
1659 |
|
1660 |
|
1661 |
|
1662 |
|
1663 |
|
1664 |
|
1665 |
|
1666 | function resolveWithKeyValue(obj, path) {
|
1667 | return isObject(obj) ? obj[path] : null;
|
1668 | }
|
1669 | |
1670 |
|
1671 |
|
1672 |
|
1673 |
|
1674 |
|
1675 |
|
1676 |
|
1677 |
|
1678 |
|
1679 |
|
1680 |
|
1681 |
|
1682 | function resolveValue(obj, path) {
|
1683 |
|
1684 | if (!isObject(obj)) {
|
1685 | return null;
|
1686 | }
|
1687 |
|
1688 | let hit = cache.get(path);
|
1689 | if (!hit) {
|
1690 | hit = parse(path);
|
1691 | if (hit) {
|
1692 | cache.set(path, hit);
|
1693 | }
|
1694 | }
|
1695 |
|
1696 | if (!hit) {
|
1697 | return null;
|
1698 | }
|
1699 |
|
1700 | const len = hit.length;
|
1701 | let last = obj;
|
1702 | let i = 0;
|
1703 | while (i < len) {
|
1704 | const val = last[hit[i]];
|
1705 | if (val === undefined) {
|
1706 | return null;
|
1707 | }
|
1708 | last = val;
|
1709 | i++;
|
1710 | }
|
1711 | return last;
|
1712 | }
|
1713 |
|
1714 | const DEFAULT_MODIFIER = (str) => str;
|
1715 | const DEFAULT_MESSAGE = (ctx) => '';
|
1716 | const DEFAULT_MESSAGE_DATA_TYPE = 'text';
|
1717 | const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
|
1718 | const DEFAULT_INTERPOLATE = toDisplayString;
|
1719 | function pluralDefault(choice, choicesLength) {
|
1720 | choice = Math.abs(choice);
|
1721 | if (choicesLength === 2) {
|
1722 |
|
1723 | return choice
|
1724 | ? choice > 1
|
1725 | ? 1
|
1726 | : 0
|
1727 | : 1;
|
1728 | }
|
1729 | return choice ? Math.min(choice, 2) : 0;
|
1730 | }
|
1731 | function getPluralIndex(options) {
|
1732 |
|
1733 | const index = isNumber(options.pluralIndex)
|
1734 | ? options.pluralIndex
|
1735 | : -1;
|
1736 |
|
1737 | return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
|
1738 | ? isNumber(options.named.count)
|
1739 | ? options.named.count
|
1740 | : isNumber(options.named.n)
|
1741 | ? options.named.n
|
1742 | : index
|
1743 | : index;
|
1744 | }
|
1745 | function normalizeNamed(pluralIndex, props) {
|
1746 | if (!props.count) {
|
1747 | props.count = pluralIndex;
|
1748 | }
|
1749 | if (!props.n) {
|
1750 | props.n = pluralIndex;
|
1751 | }
|
1752 | }
|
1753 | function createMessageContext(options = {}) {
|
1754 | const locale = options.locale;
|
1755 | const pluralIndex = getPluralIndex(options);
|
1756 | const pluralRule = isObject(options.pluralRules) &&
|
1757 | isString(locale) &&
|
1758 | isFunction(options.pluralRules[locale])
|
1759 | ? options.pluralRules[locale]
|
1760 | : pluralDefault;
|
1761 | const orgPluralRule = isObject(options.pluralRules) &&
|
1762 | isString(locale) &&
|
1763 | isFunction(options.pluralRules[locale])
|
1764 | ? pluralDefault
|
1765 | : undefined;
|
1766 | const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
|
1767 | const _list = options.list || [];
|
1768 | const list = (index) => _list[index];
|
1769 |
|
1770 | const _named = options.named || {};
|
1771 | isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
|
1772 | const named = (key) => _named[key];
|
1773 |
|
1774 | function message(key) {
|
1775 |
|
1776 | const msg = isFunction(options.messages)
|
1777 | ? options.messages(key)
|
1778 | : isObject(options.messages)
|
1779 | ? options.messages[key]
|
1780 | : false;
|
1781 | return !msg
|
1782 | ? options.parent
|
1783 | ? options.parent.message(key)
|
1784 | : DEFAULT_MESSAGE
|
1785 | : msg;
|
1786 | }
|
1787 | const _modifier = (name) => options.modifiers
|
1788 | ? options.modifiers[name]
|
1789 | : DEFAULT_MODIFIER;
|
1790 | const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
|
1791 | ? options.processor.normalize
|
1792 | : DEFAULT_NORMALIZE;
|
1793 | const interpolate = isPlainObject(options.processor) &&
|
1794 | isFunction(options.processor.interpolate)
|
1795 | ? options.processor.interpolate
|
1796 | : DEFAULT_INTERPOLATE;
|
1797 | const type = isPlainObject(options.processor) && isString(options.processor.type)
|
1798 | ? options.processor.type
|
1799 | : DEFAULT_MESSAGE_DATA_TYPE;
|
1800 | const ctx = {
|
1801 | ["list" ]: list,
|
1802 | ["named" ]: named,
|
1803 | ["plural" ]: plural,
|
1804 | ["linked" ]: (key, modifier) => {
|
1805 |
|
1806 | const msg = message(key)(ctx);
|
1807 | return isString(modifier) ? _modifier(modifier)(msg) : msg;
|
1808 | },
|
1809 | ["message" ]: message,
|
1810 | ["type" ]: type,
|
1811 | ["interpolate" ]: interpolate,
|
1812 | ["normalize" ]: normalize
|
1813 | };
|
1814 | return ctx;
|
1815 | }
|
1816 |
|
1817 | const IntlifyDevToolsHooks = {
|
1818 | I18nInit: 'i18n:init',
|
1819 | FunctionTranslate: 'function:translate'
|
1820 | };
|
1821 |
|
1822 | let devtools = null;
|
1823 | function setDevToolsHook(hook) {
|
1824 | devtools = hook;
|
1825 | }
|
1826 | function initI18nDevTools(i18n, version, meta) {
|
1827 |
|
1828 | devtools &&
|
1829 | devtools.emit(IntlifyDevToolsHooks.I18nInit, {
|
1830 | timestamp: Date.now(),
|
1831 | i18n,
|
1832 | version,
|
1833 | meta
|
1834 | });
|
1835 | }
|
1836 | const translateDevTools = createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
|
1837 | function createDevToolsHook(hook) {
|
1838 | return (payloads) => devtools && devtools.emit(hook, payloads);
|
1839 | }
|
1840 |
|
1841 | const CoreWarnCodes = {
|
1842 | NOT_FOUND_KEY: 1,
|
1843 | FALLBACK_TO_TRANSLATE: 2,
|
1844 | CANNOT_FORMAT_NUMBER: 3,
|
1845 | FALLBACK_TO_NUMBER_FORMAT: 4,
|
1846 | CANNOT_FORMAT_DATE: 5,
|
1847 | FALLBACK_TO_DATE_FORMAT: 6,
|
1848 | __EXTEND_POINT__: 7
|
1849 | };
|
1850 |
|
1851 | const warnMessages$1 = {
|
1852 | [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
|
1853 | [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
|
1854 | [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
|
1855 | [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
|
1856 | [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
|
1857 | [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
|
1858 | };
|
1859 | function getWarnMessage$1(code, ...args) {
|
1860 | return format(warnMessages$1[code], ...args);
|
1861 | }
|
1862 |
|
1863 | |
1864 |
|
1865 |
|
1866 |
|
1867 |
|
1868 |
|
1869 |
|
1870 |
|
1871 |
|
1872 |
|
1873 |
|
1874 |
|
1875 |
|
1876 |
|
1877 |
|
1878 |
|
1879 | function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
|
1880 | ) {
|
1881 |
|
1882 | return [...new Set([
|
1883 | start,
|
1884 | ...(isArray(fallback)
|
1885 | ? fallback
|
1886 | : isObject(fallback)
|
1887 | ? Object.keys(fallback)
|
1888 | : isString(fallback)
|
1889 | ? [fallback]
|
1890 | : [start])
|
1891 | ])];
|
1892 | }
|
1893 | |
1894 |
|
1895 |
|
1896 |
|
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 |
|
1902 |
|
1903 |
|
1904 |
|
1905 |
|
1906 |
|
1907 |
|
1908 |
|
1909 | function fallbackWithLocaleChain(ctx, fallback, start) {
|
1910 | const startLocale = isString(start) ? start : DEFAULT_LOCALE;
|
1911 | const context = ctx;
|
1912 | if (!context.__localeChainCache) {
|
1913 | context.__localeChainCache = new Map();
|
1914 | }
|
1915 | let chain = context.__localeChainCache.get(startLocale);
|
1916 | if (!chain) {
|
1917 | chain = [];
|
1918 |
|
1919 | let block = [start];
|
1920 |
|
1921 | while (isArray(block)) {
|
1922 | block = appendBlockToChain(chain, block, fallback);
|
1923 | }
|
1924 |
|
1925 |
|
1926 | const defaults = isArray(fallback) || !isPlainObject(fallback)
|
1927 | ? fallback
|
1928 | : fallback['default']
|
1929 | ? fallback['default']
|
1930 | : null;
|
1931 |
|
1932 | block = isString(defaults) ? [defaults] : defaults;
|
1933 | if (isArray(block)) {
|
1934 | appendBlockToChain(chain, block, false);
|
1935 | }
|
1936 | context.__localeChainCache.set(startLocale, chain);
|
1937 | }
|
1938 | return chain;
|
1939 | }
|
1940 | function appendBlockToChain(chain, block, blocks) {
|
1941 | let follow = true;
|
1942 | for (let i = 0; i < block.length && isBoolean(follow); i++) {
|
1943 | const locale = block[i];
|
1944 | if (isString(locale)) {
|
1945 | follow = appendLocaleToChain(chain, block[i], blocks);
|
1946 | }
|
1947 | }
|
1948 | return follow;
|
1949 | }
|
1950 | function appendLocaleToChain(chain, locale, blocks) {
|
1951 | let follow;
|
1952 | const tokens = locale.split('-');
|
1953 | do {
|
1954 | const target = tokens.join('-');
|
1955 | follow = appendItemToChain(chain, target, blocks);
|
1956 | tokens.splice(-1, 1);
|
1957 | } while (tokens.length && follow === true);
|
1958 | return follow;
|
1959 | }
|
1960 | function appendItemToChain(chain, target, blocks) {
|
1961 | let follow = false;
|
1962 | if (!chain.includes(target)) {
|
1963 | follow = true;
|
1964 | if (target) {
|
1965 | follow = target[target.length - 1] !== '!';
|
1966 | const locale = target.replace(/!/g, '');
|
1967 | chain.push(locale);
|
1968 | if ((isArray(blocks) || isPlainObject(blocks)) &&
|
1969 | blocks[locale]
|
1970 | ) {
|
1971 |
|
1972 | follow = blocks[locale];
|
1973 | }
|
1974 | }
|
1975 | }
|
1976 | return follow;
|
1977 | }
|
1978 |
|
1979 |
|
1980 | |
1981 |
|
1982 |
|
1983 |
|
1984 | const VERSION$1 = '9.2.0-beta.6';
|
1985 | const NOT_REOSLVED = -1;
|
1986 | const DEFAULT_LOCALE = 'en-US';
|
1987 | const MISSING_RESOLVE_VALUE = '';
|
1988 | function getDefaultLinkedModifiers() {
|
1989 | return {
|
1990 | upper: (val) => (isString(val) ? val.toUpperCase() : val),
|
1991 | lower: (val) => (isString(val) ? val.toLowerCase() : val),
|
1992 |
|
1993 | capitalize: (val) => (isString(val)
|
1994 | ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
|
1995 | : val)
|
1996 | };
|
1997 | }
|
1998 | let _compiler;
|
1999 | function registerMessageCompiler(compiler) {
|
2000 | _compiler = compiler;
|
2001 | }
|
2002 | let _resolver;
|
2003 | |
2004 |
|
2005 |
|
2006 |
|
2007 |
|
2008 |
|
2009 |
|
2010 | function registerMessageResolver(resolver) {
|
2011 | _resolver = resolver;
|
2012 | }
|
2013 | let _fallbacker;
|
2014 | |
2015 |
|
2016 |
|
2017 |
|
2018 |
|
2019 |
|
2020 |
|
2021 | function registerLocaleFallbacker(fallbacker) {
|
2022 | _fallbacker = fallbacker;
|
2023 | }
|
2024 |
|
2025 | let _additionalMeta = null;
|
2026 | const setAdditionalMeta = (meta) => {
|
2027 | _additionalMeta = meta;
|
2028 | };
|
2029 | const getAdditionalMeta = () => _additionalMeta;
|
2030 |
|
2031 | let _cid = 0;
|
2032 | function createCoreContext(options = {}) {
|
2033 |
|
2034 | const version = isString(options.version) ? options.version : VERSION$1;
|
2035 | const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
|
2036 | const fallbackLocale = isArray(options.fallbackLocale) ||
|
2037 | isPlainObject(options.fallbackLocale) ||
|
2038 | isString(options.fallbackLocale) ||
|
2039 | options.fallbackLocale === false
|
2040 | ? options.fallbackLocale
|
2041 | : locale;
|
2042 | const messages = isPlainObject(options.messages)
|
2043 | ? options.messages
|
2044 | : { [locale]: {} };
|
2045 | const datetimeFormats = isPlainObject(options.datetimeFormats)
|
2046 | ? options.datetimeFormats
|
2047 | : { [locale]: {} }
|
2048 | ;
|
2049 | const numberFormats = isPlainObject(options.numberFormats)
|
2050 | ? options.numberFormats
|
2051 | : { [locale]: {} }
|
2052 | ;
|
2053 | const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
|
2054 | const pluralRules = options.pluralRules || {};
|
2055 | const missing = isFunction(options.missing) ? options.missing : null;
|
2056 | const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
|
2057 | ? options.missingWarn
|
2058 | : true;
|
2059 | const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
|
2060 | ? options.fallbackWarn
|
2061 | : true;
|
2062 | const fallbackFormat = !!options.fallbackFormat;
|
2063 | const unresolving = !!options.unresolving;
|
2064 | const postTranslation = isFunction(options.postTranslation)
|
2065 | ? options.postTranslation
|
2066 | : null;
|
2067 | const processor = isPlainObject(options.processor) ? options.processor : null;
|
2068 | const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
2069 | ? options.warnHtmlMessage
|
2070 | : true;
|
2071 | const escapeParameter = !!options.escapeParameter;
|
2072 | const messageCompiler = isFunction(options.messageCompiler)
|
2073 | ? options.messageCompiler
|
2074 | : _compiler;
|
2075 | const messageResolver = isFunction(options.messageResolver)
|
2076 | ? options.messageResolver
|
2077 | : _resolver || resolveWithKeyValue;
|
2078 | const localeFallbacker = isFunction(options.localeFallbacker)
|
2079 | ? options.localeFallbacker
|
2080 | : _fallbacker || fallbackWithSimple;
|
2081 | const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
|
2082 |
|
2083 | const internalOptions = options;
|
2084 | const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
|
2085 | ? internalOptions.__datetimeFormatters
|
2086 | : new Map()
|
2087 | ;
|
2088 | const __numberFormatters = isObject(internalOptions.__numberFormatters)
|
2089 | ? internalOptions.__numberFormatters
|
2090 | : new Map()
|
2091 | ;
|
2092 | const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
|
2093 | _cid++;
|
2094 | const context = {
|
2095 | version,
|
2096 | cid: _cid,
|
2097 | locale,
|
2098 | fallbackLocale,
|
2099 | messages,
|
2100 | modifiers,
|
2101 | pluralRules,
|
2102 | missing,
|
2103 | missingWarn,
|
2104 | fallbackWarn,
|
2105 | fallbackFormat,
|
2106 | unresolving,
|
2107 | postTranslation,
|
2108 | processor,
|
2109 | warnHtmlMessage,
|
2110 | escapeParameter,
|
2111 | messageCompiler,
|
2112 | messageResolver,
|
2113 | localeFallbacker,
|
2114 | onWarn,
|
2115 | __meta
|
2116 | };
|
2117 | {
|
2118 | context.datetimeFormats = datetimeFormats;
|
2119 | context.numberFormats = numberFormats;
|
2120 | context.__datetimeFormatters = __datetimeFormatters;
|
2121 | context.__numberFormatters = __numberFormatters;
|
2122 | }
|
2123 |
|
2124 | {
|
2125 | initI18nDevTools(context, version, __meta);
|
2126 | }
|
2127 | return context;
|
2128 | }
|
2129 |
|
2130 | function isTranslateFallbackWarn(fallback, key) {
|
2131 | return fallback instanceof RegExp ? fallback.test(key) : fallback;
|
2132 | }
|
2133 |
|
2134 | function isTranslateMissingWarn(missing, key) {
|
2135 | return missing instanceof RegExp ? missing.test(key) : missing;
|
2136 | }
|
2137 |
|
2138 | function handleMissing(context, key, locale, missingWarn, type) {
|
2139 | const { missing, onWarn } = context;
|
2140 | if (missing !== null) {
|
2141 | const ret = missing(context, locale, key, type);
|
2142 | return isString(ret) ? ret : key;
|
2143 | }
|
2144 | else {
|
2145 | if (isTranslateMissingWarn(missingWarn, key)) {
|
2146 | onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
|
2147 | }
|
2148 | return key;
|
2149 | }
|
2150 | }
|
2151 |
|
2152 | function updateFallbackLocale(ctx, locale, fallback) {
|
2153 | const context = ctx;
|
2154 | context.__localeChainCache = new Map();
|
2155 | ctx.localeFallbacker(ctx, fallback, locale);
|
2156 | }
|
2157 |
|
2158 |
|
2159 | const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
|
2160 | const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
|
2161 | function checkHtmlMessage(source, options) {
|
2162 | const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
2163 | ? options.warnHtmlMessage
|
2164 | : true;
|
2165 | if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
|
2166 | warn(format(WARN_MESSAGE, { source }));
|
2167 | }
|
2168 | }
|
2169 | const defaultOnCacheKey = (source) => source;
|
2170 | let compileCache = Object.create(null);
|
2171 | function compileToFunction(source, options = {}) {
|
2172 | {
|
2173 |
|
2174 | checkHtmlMessage(source, options);
|
2175 |
|
2176 | const onCacheKey = options.onCacheKey || defaultOnCacheKey;
|
2177 | const key = onCacheKey(source);
|
2178 | const cached = compileCache[key];
|
2179 | if (cached) {
|
2180 | return cached;
|
2181 | }
|
2182 |
|
2183 | let occurred = false;
|
2184 | const onError = options.onError || defaultOnError;
|
2185 | options.onError = (err) => {
|
2186 | occurred = true;
|
2187 | onError(err);
|
2188 | };
|
2189 |
|
2190 | const { code } = baseCompile(source, options);
|
2191 |
|
2192 | const msg = new Function(`return ${code}`)();
|
2193 |
|
2194 | return !occurred ? (compileCache[key] = msg) : msg;
|
2195 | }
|
2196 | }
|
2197 |
|
2198 | let code$2 = CompileErrorCodes.__EXTEND_POINT__;
|
2199 | const inc$2 = () => code$2++;
|
2200 | const CoreErrorCodes = {
|
2201 | INVALID_ARGUMENT: code$2,
|
2202 | INVALID_DATE_ARGUMENT: inc$2(),
|
2203 | INVALID_ISO_DATE_ARGUMENT: inc$2(),
|
2204 | __EXTEND_POINT__: inc$2()
|
2205 | };
|
2206 | function createCoreError(code) {
|
2207 | return createCompileError(code, null, { messages: errorMessages$1 } );
|
2208 | }
|
2209 |
|
2210 | const errorMessages$1 = {
|
2211 | [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
|
2212 | [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
|
2213 | 'Make sure your Date represents a valid date.',
|
2214 | [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
|
2215 | };
|
2216 |
|
2217 | const NOOP_MESSAGE_FUNCTION = () => '';
|
2218 | const isMessageFunction = (val) => isFunction(val);
|
2219 |
|
2220 | function translate(context, ...args) {
|
2221 | const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
|
2222 | const [key, options] = parseTranslateArgs(...args);
|
2223 | const missingWarn = isBoolean(options.missingWarn)
|
2224 | ? options.missingWarn
|
2225 | : context.missingWarn;
|
2226 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2227 | ? options.fallbackWarn
|
2228 | : context.fallbackWarn;
|
2229 | const escapeParameter = isBoolean(options.escapeParameter)
|
2230 | ? options.escapeParameter
|
2231 | : context.escapeParameter;
|
2232 | const resolvedMessage = !!options.resolvedMessage;
|
2233 |
|
2234 | const defaultMsgOrKey = isString(options.default) || isBoolean(options.default)
|
2235 | ? !isBoolean(options.default)
|
2236 | ? options.default
|
2237 | : key
|
2238 | : fallbackFormat
|
2239 | ? key
|
2240 | : '';
|
2241 | const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
|
2242 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2243 |
|
2244 | escapeParameter && escapeParams(options);
|
2245 |
|
2246 |
|
2247 | let [format, targetLocale, message] = !resolvedMessage
|
2248 | ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
|
2249 | : [
|
2250 | key,
|
2251 | locale,
|
2252 | messages[locale] || {}
|
2253 | ];
|
2254 |
|
2255 | let cacheBaseKey = key;
|
2256 | if (!resolvedMessage &&
|
2257 | !(isString(format) || isMessageFunction(format))) {
|
2258 | if (enableDefaultMsg) {
|
2259 | format = defaultMsgOrKey;
|
2260 | cacheBaseKey = format;
|
2261 | }
|
2262 | }
|
2263 |
|
2264 | if (!resolvedMessage &&
|
2265 | (!(isString(format) || isMessageFunction(format)) ||
|
2266 | !isString(targetLocale))) {
|
2267 | return unresolving ? NOT_REOSLVED : key;
|
2268 | }
|
2269 | if (isString(format) && context.messageCompiler == null) {
|
2270 | warn(`The message format compilation is not supported in this build. ` +
|
2271 | `Because message compiler isn't included. ` +
|
2272 | `You need to pre-compilation all message format. ` +
|
2273 | `So translate function return '${key}'.`);
|
2274 | return key;
|
2275 | }
|
2276 |
|
2277 | let occurred = false;
|
2278 | const errorDetector = () => {
|
2279 | occurred = true;
|
2280 | };
|
2281 |
|
2282 | const msg = !isMessageFunction(format)
|
2283 | ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
|
2284 | : format;
|
2285 |
|
2286 | if (occurred) {
|
2287 | return format;
|
2288 | }
|
2289 |
|
2290 | const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
|
2291 | const msgContext = createMessageContext(ctxOptions);
|
2292 | const messaged = evaluateMessage(context, msg, msgContext);
|
2293 |
|
2294 | const ret = postTranslation ? postTranslation(messaged) : messaged;
|
2295 |
|
2296 | {
|
2297 |
|
2298 | const payloads = {
|
2299 | timestamp: Date.now(),
|
2300 | key: isString(key)
|
2301 | ? key
|
2302 | : isMessageFunction(format)
|
2303 | ? format.key
|
2304 | : '',
|
2305 | locale: targetLocale || (isMessageFunction(format)
|
2306 | ? format.locale
|
2307 | : ''),
|
2308 | format: isString(format)
|
2309 | ? format
|
2310 | : isMessageFunction(format)
|
2311 | ? format.source
|
2312 | : '',
|
2313 | message: ret
|
2314 | };
|
2315 | payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
|
2316 | translateDevTools(payloads);
|
2317 | }
|
2318 | return ret;
|
2319 | }
|
2320 | function escapeParams(options) {
|
2321 | if (isArray(options.list)) {
|
2322 | options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
|
2323 | }
|
2324 | else if (isObject(options.named)) {
|
2325 | Object.keys(options.named).forEach(key => {
|
2326 | if (isString(options.named[key])) {
|
2327 | options.named[key] = escapeHtml(options.named[key]);
|
2328 | }
|
2329 | });
|
2330 | }
|
2331 | }
|
2332 | function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
|
2333 | const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
|
2334 | const locales = localeFallbacker(context, fallbackLocale, locale);
|
2335 | let message = {};
|
2336 | let targetLocale;
|
2337 | let format = null;
|
2338 | const type = 'translate';
|
2339 | for (let i = 0; i < locales.length; i++) {
|
2340 | targetLocale = locales[i];
|
2341 | if (locale !== targetLocale &&
|
2342 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2343 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
|
2344 | key,
|
2345 | target: targetLocale
|
2346 | }));
|
2347 | }
|
2348 | message =
|
2349 | messages[targetLocale] || {};
|
2350 | let startTag;
|
2351 | if (inBrowser) {
|
2352 | window.performance.now();
|
2353 | startTag = 'intlify-message-resolve-start';
|
2354 | mark && mark(startTag);
|
2355 | }
|
2356 | if ((format = resolveValue(message, key)) === null) {
|
2357 |
|
2358 | format = message[key];
|
2359 | }
|
2360 | if (isString(format) || isFunction(format))
|
2361 | break;
|
2362 | const missingRet = handleMissing(context,
|
2363 | key, targetLocale, missingWarn, type);
|
2364 | if (missingRet !== key) {
|
2365 | format = missingRet;
|
2366 | }
|
2367 | }
|
2368 | return [format, targetLocale, message];
|
2369 | }
|
2370 | function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
|
2371 | const { messageCompiler, warnHtmlMessage } = context;
|
2372 | if (isMessageFunction(format)) {
|
2373 | const msg = format;
|
2374 | msg.locale = msg.locale || targetLocale;
|
2375 | msg.key = msg.key || key;
|
2376 | return msg;
|
2377 | }
|
2378 | let startTag;
|
2379 | if (inBrowser) {
|
2380 | window.performance.now();
|
2381 | startTag = 'intlify-message-compilation-start';
|
2382 | mark && mark(startTag);
|
2383 | }
|
2384 | const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
|
2385 | msg.locale = targetLocale;
|
2386 | msg.key = key;
|
2387 | msg.source = format;
|
2388 | return msg;
|
2389 | }
|
2390 | function evaluateMessage(context, msg, msgCtx) {
|
2391 | let startTag;
|
2392 | if (inBrowser) {
|
2393 | window.performance.now();
|
2394 | startTag = 'intlify-message-evaluation-start';
|
2395 | mark && mark(startTag);
|
2396 | }
|
2397 | const messaged = msg(msgCtx);
|
2398 | return messaged;
|
2399 | }
|
2400 |
|
2401 | function parseTranslateArgs(...args) {
|
2402 | const [arg1, arg2, arg3] = args;
|
2403 | const options = {};
|
2404 | if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
|
2405 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2406 | }
|
2407 |
|
2408 | const key = isNumber(arg1)
|
2409 | ? String(arg1)
|
2410 | : isMessageFunction(arg1)
|
2411 | ? arg1
|
2412 | : arg1;
|
2413 | if (isNumber(arg2)) {
|
2414 | options.plural = arg2;
|
2415 | }
|
2416 | else if (isString(arg2)) {
|
2417 | options.default = arg2;
|
2418 | }
|
2419 | else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
|
2420 | options.named = arg2;
|
2421 | }
|
2422 | else if (isArray(arg2)) {
|
2423 | options.list = arg2;
|
2424 | }
|
2425 | if (isNumber(arg3)) {
|
2426 | options.plural = arg3;
|
2427 | }
|
2428 | else if (isString(arg3)) {
|
2429 | options.default = arg3;
|
2430 | }
|
2431 | else if (isPlainObject(arg3)) {
|
2432 | assign(options, arg3);
|
2433 | }
|
2434 | return [key, options];
|
2435 | }
|
2436 | function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
|
2437 | return {
|
2438 | warnHtmlMessage,
|
2439 | onError: (err) => {
|
2440 | errorDetector && errorDetector(err);
|
2441 | {
|
2442 | throw err;
|
2443 | }
|
2444 | },
|
2445 | onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
|
2446 | };
|
2447 | }
|
2448 | function getMessageContextOptions(context, locale, message, options) {
|
2449 | const { modifiers, pluralRules, messageResolver: resolveValue } = context;
|
2450 | const resolveMessage = (key) => {
|
2451 | const val = resolveValue(message, key);
|
2452 | if (isString(val)) {
|
2453 | let occurred = false;
|
2454 | const errorDetector = () => {
|
2455 | occurred = true;
|
2456 | };
|
2457 | const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
|
2458 | return !occurred
|
2459 | ? msg
|
2460 | : NOOP_MESSAGE_FUNCTION;
|
2461 | }
|
2462 | else if (isMessageFunction(val)) {
|
2463 | return val;
|
2464 | }
|
2465 | else {
|
2466 |
|
2467 | return NOOP_MESSAGE_FUNCTION;
|
2468 | }
|
2469 | };
|
2470 | const ctxOptions = {
|
2471 | locale,
|
2472 | modifiers,
|
2473 | pluralRules,
|
2474 | messages: resolveMessage
|
2475 | };
|
2476 | if (context.processor) {
|
2477 | ctxOptions.processor = context.processor;
|
2478 | }
|
2479 | if (options.list) {
|
2480 | ctxOptions.list = options.list;
|
2481 | }
|
2482 | if (options.named) {
|
2483 | ctxOptions.named = options.named;
|
2484 | }
|
2485 | if (isNumber(options.plural)) {
|
2486 | ctxOptions.pluralIndex = options.plural;
|
2487 | }
|
2488 | return ctxOptions;
|
2489 | }
|
2490 |
|
2491 | const intlDefined = typeof Intl !== 'undefined';
|
2492 | const Availabilities = {
|
2493 | dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
|
2494 | numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
|
2495 | };
|
2496 |
|
2497 |
|
2498 | function datetime(context, ...args) {
|
2499 | const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
|
2500 | const { __datetimeFormatters } = context;
|
2501 | if (!Availabilities.dateTimeFormat) {
|
2502 | onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
|
2503 | return MISSING_RESOLVE_VALUE;
|
2504 | }
|
2505 | const [key, value, options, overrides] = parseDateTimeArgs(...args);
|
2506 | const missingWarn = isBoolean(options.missingWarn)
|
2507 | ? options.missingWarn
|
2508 | : context.missingWarn;
|
2509 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2510 | ? options.fallbackWarn
|
2511 | : context.fallbackWarn;
|
2512 | const part = !!options.part;
|
2513 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2514 | const locales = localeFallbacker(context,
|
2515 | fallbackLocale, locale);
|
2516 | if (!isString(key) || key === '') {
|
2517 | return new Intl.DateTimeFormat(locale).format(value);
|
2518 | }
|
2519 |
|
2520 | let datetimeFormat = {};
|
2521 | let targetLocale;
|
2522 | let format = null;
|
2523 | const type = 'datetime format';
|
2524 | for (let i = 0; i < locales.length; i++) {
|
2525 | targetLocale = locales[i];
|
2526 | if (locale !== targetLocale &&
|
2527 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2528 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
|
2529 | key,
|
2530 | target: targetLocale
|
2531 | }));
|
2532 | }
|
2533 | datetimeFormat =
|
2534 | datetimeFormats[targetLocale] || {};
|
2535 | format = datetimeFormat[key];
|
2536 | if (isPlainObject(format))
|
2537 | break;
|
2538 | handleMissing(context, key, targetLocale, missingWarn, type);
|
2539 | }
|
2540 |
|
2541 | if (!isPlainObject(format) || !isString(targetLocale)) {
|
2542 | return unresolving ? NOT_REOSLVED : key;
|
2543 | }
|
2544 | let id = `${targetLocale}__${key}`;
|
2545 | if (!isEmptyObject(overrides)) {
|
2546 | id = `${id}__${JSON.stringify(overrides)}`;
|
2547 | }
|
2548 | let formatter = __datetimeFormatters.get(id);
|
2549 | if (!formatter) {
|
2550 | formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
|
2551 | __datetimeFormatters.set(id, formatter);
|
2552 | }
|
2553 | return !part ? formatter.format(value) : formatter.formatToParts(value);
|
2554 | }
|
2555 |
|
2556 | function parseDateTimeArgs(...args) {
|
2557 | const [arg1, arg2, arg3, arg4] = args;
|
2558 | let options = {};
|
2559 | let overrides = {};
|
2560 | let value;
|
2561 | if (isString(arg1)) {
|
2562 |
|
2563 |
|
2564 | const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
|
2565 | if (!matches) {
|
2566 | throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
|
2567 | }
|
2568 |
|
2569 |
|
2570 | const dateTime = matches[3]
|
2571 | ? matches[3].trim().startsWith('T')
|
2572 | ? `${matches[1].trim()}${matches[3].trim()}`
|
2573 | : `${matches[1].trim()}T${matches[3].trim()}`
|
2574 | : matches[1].trim();
|
2575 | value = new Date(dateTime);
|
2576 | try {
|
2577 |
|
2578 | value.toISOString();
|
2579 | }
|
2580 | catch (e) {
|
2581 | throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
|
2582 | }
|
2583 | }
|
2584 | else if (isDate(arg1)) {
|
2585 | if (isNaN(arg1.getTime())) {
|
2586 | throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
|
2587 | }
|
2588 | value = arg1;
|
2589 | }
|
2590 | else if (isNumber(arg1)) {
|
2591 | value = arg1;
|
2592 | }
|
2593 | else {
|
2594 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2595 | }
|
2596 | if (isString(arg2)) {
|
2597 | options.key = arg2;
|
2598 | }
|
2599 | else if (isPlainObject(arg2)) {
|
2600 | options = arg2;
|
2601 | }
|
2602 | if (isString(arg3)) {
|
2603 | options.locale = arg3;
|
2604 | }
|
2605 | else if (isPlainObject(arg3)) {
|
2606 | overrides = arg3;
|
2607 | }
|
2608 | if (isPlainObject(arg4)) {
|
2609 | overrides = arg4;
|
2610 | }
|
2611 | return [options.key || '', value, options, overrides];
|
2612 | }
|
2613 |
|
2614 | function clearDateTimeFormat(ctx, locale, format) {
|
2615 | const context = ctx;
|
2616 | for (const key in format) {
|
2617 | const id = `${locale}__${key}`;
|
2618 | if (!context.__datetimeFormatters.has(id)) {
|
2619 | continue;
|
2620 | }
|
2621 | context.__datetimeFormatters.delete(id);
|
2622 | }
|
2623 | }
|
2624 |
|
2625 |
|
2626 | function number(context, ...args) {
|
2627 | const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
|
2628 | const { __numberFormatters } = context;
|
2629 | if (!Availabilities.numberFormat) {
|
2630 | onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
|
2631 | return MISSING_RESOLVE_VALUE;
|
2632 | }
|
2633 | const [key, value, options, overrides] = parseNumberArgs(...args);
|
2634 | const missingWarn = isBoolean(options.missingWarn)
|
2635 | ? options.missingWarn
|
2636 | : context.missingWarn;
|
2637 | const fallbackWarn = isBoolean(options.fallbackWarn)
|
2638 | ? options.fallbackWarn
|
2639 | : context.fallbackWarn;
|
2640 | const part = !!options.part;
|
2641 | const locale = isString(options.locale) ? options.locale : context.locale;
|
2642 | const locales = localeFallbacker(context,
|
2643 | fallbackLocale, locale);
|
2644 | if (!isString(key) || key === '') {
|
2645 | return new Intl.NumberFormat(locale).format(value);
|
2646 | }
|
2647 |
|
2648 | let numberFormat = {};
|
2649 | let targetLocale;
|
2650 | let format = null;
|
2651 | const type = 'number format';
|
2652 | for (let i = 0; i < locales.length; i++) {
|
2653 | targetLocale = locales[i];
|
2654 | if (locale !== targetLocale &&
|
2655 | isTranslateFallbackWarn(fallbackWarn, key)) {
|
2656 | onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
|
2657 | key,
|
2658 | target: targetLocale
|
2659 | }));
|
2660 | }
|
2661 | numberFormat =
|
2662 | numberFormats[targetLocale] || {};
|
2663 | format = numberFormat[key];
|
2664 | if (isPlainObject(format))
|
2665 | break;
|
2666 | handleMissing(context, key, targetLocale, missingWarn, type);
|
2667 | }
|
2668 |
|
2669 | if (!isPlainObject(format) || !isString(targetLocale)) {
|
2670 | return unresolving ? NOT_REOSLVED : key;
|
2671 | }
|
2672 | let id = `${targetLocale}__${key}`;
|
2673 | if (!isEmptyObject(overrides)) {
|
2674 | id = `${id}__${JSON.stringify(overrides)}`;
|
2675 | }
|
2676 | let formatter = __numberFormatters.get(id);
|
2677 | if (!formatter) {
|
2678 | formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
|
2679 | __numberFormatters.set(id, formatter);
|
2680 | }
|
2681 | return !part ? formatter.format(value) : formatter.formatToParts(value);
|
2682 | }
|
2683 |
|
2684 | function parseNumberArgs(...args) {
|
2685 | const [arg1, arg2, arg3, arg4] = args;
|
2686 | let options = {};
|
2687 | let overrides = {};
|
2688 | if (!isNumber(arg1)) {
|
2689 | throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
|
2690 | }
|
2691 | const value = arg1;
|
2692 | if (isString(arg2)) {
|
2693 | options.key = arg2;
|
2694 | }
|
2695 | else if (isPlainObject(arg2)) {
|
2696 | options = arg2;
|
2697 | }
|
2698 | if (isString(arg3)) {
|
2699 | options.locale = arg3;
|
2700 | }
|
2701 | else if (isPlainObject(arg3)) {
|
2702 | overrides = arg3;
|
2703 | }
|
2704 | if (isPlainObject(arg4)) {
|
2705 | overrides = arg4;
|
2706 | }
|
2707 | return [options.key || '', value, options, overrides];
|
2708 | }
|
2709 |
|
2710 | function clearNumberFormat(ctx, locale, format) {
|
2711 | const context = ctx;
|
2712 | for (const key in format) {
|
2713 | const id = `${locale}__${key}`;
|
2714 | if (!context.__numberFormatters.has(id)) {
|
2715 | continue;
|
2716 | }
|
2717 | context.__numberFormatters.delete(id);
|
2718 | }
|
2719 | }
|
2720 |
|
2721 | |
2722 |
|
2723 |
|
2724 |
|
2725 |
|
2726 |
|
2727 |
|
2728 |
|
2729 | const VERSION = '9.2.0-beta.6';
|
2730 | |
2731 |
|
2732 |
|
2733 |
|
2734 | function initDev() {
|
2735 | {
|
2736 | {
|
2737 | console.info(`You are running a development build of vue-i18n.\n` +
|
2738 | `Make sure to use the production build (*.prod.js) when deploying for production.`);
|
2739 | }
|
2740 | }
|
2741 | }
|
2742 |
|
2743 | let code$1 = CoreWarnCodes.__EXTEND_POINT__;
|
2744 | const inc$1 = () => code$1++;
|
2745 | const I18nWarnCodes = {
|
2746 | FALLBACK_TO_ROOT: code$1,
|
2747 | NOT_SUPPORTED_PRESERVE: inc$1(),
|
2748 | NOT_SUPPORTED_FORMATTER: inc$1(),
|
2749 | NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(),
|
2750 | NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(),
|
2751 | COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(),
|
2752 | NOT_FOUND_PARENT_SCOPE: inc$1(),
|
2753 | NOT_SUPPORT_MULTI_I18N_INSTANCE: inc$1()
|
2754 | };
|
2755 | const warnMessages = {
|
2756 | [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
|
2757 | [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
|
2758 | [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
|
2759 | [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
|
2760 | [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
|
2761 | [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
|
2762 | [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
|
2763 | [I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE]: `Not support multi i18n instance.`
|
2764 | };
|
2765 | function getWarnMessage(code, ...args) {
|
2766 | return format(warnMessages[code], ...args);
|
2767 | }
|
2768 |
|
2769 | let code = CompileErrorCodes.__EXTEND_POINT__;
|
2770 | const inc = () => code++;
|
2771 | const I18nErrorCodes = {
|
2772 |
|
2773 | UNEXPECTED_RETURN_TYPE: code,
|
2774 |
|
2775 | INVALID_ARGUMENT: inc(),
|
2776 |
|
2777 | MUST_BE_CALL_SETUP_TOP: inc(),
|
2778 | NOT_INSLALLED: inc(),
|
2779 | NOT_AVAILABLE_IN_LEGACY_MODE: inc(),
|
2780 |
|
2781 | REQUIRED_VALUE: inc(),
|
2782 | INVALID_VALUE: inc(),
|
2783 |
|
2784 | CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(),
|
2785 | NOT_INSLALLED_WITH_PROVIDE: inc(),
|
2786 |
|
2787 | UNEXPECTED_ERROR: inc(),
|
2788 |
|
2789 | NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(),
|
2790 |
|
2791 | BRIDGE_SUPPORT_VUE_2_ONLY: inc(),
|
2792 |
|
2793 | __EXTEND_POINT__: inc()
|
2794 | };
|
2795 | function createI18nError(code, ...args) {
|
2796 | return createCompileError(code, null, { messages: errorMessages, args } );
|
2797 | }
|
2798 | const errorMessages = {
|
2799 | [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
|
2800 | [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
|
2801 | [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
|
2802 | [I18nErrorCodes.NOT_INSLALLED]: 'Need to install with `app.use` function',
|
2803 | [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
|
2804 | [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
|
2805 | [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
|
2806 | [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
|
2807 | [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
|
2808 | [I18nErrorCodes.NOT_INSLALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
|
2809 | [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
|
2810 | [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only'
|
2811 | };
|
2812 |
|
2813 | const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
|
2814 | const LegacyInstanceSymbol = makeSymbol('__legacyVueI18n');
|
2815 |
|
2816 |
|
2817 |
|
2818 | function isLegacyVueI18n(VueI18n) {
|
2819 | if (VueI18n == null || VueI18n.version == null) {
|
2820 | return false;
|
2821 | }
|
2822 | return (Number(VueI18n.version.split('.')[0]) || -1) >= 8;
|
2823 | }
|
2824 | |
2825 |
|
2826 |
|
2827 | function handleFlatJson(obj) {
|
2828 |
|
2829 | if (!isObject(obj)) {
|
2830 | return obj;
|
2831 | }
|
2832 | for (const key in obj) {
|
2833 |
|
2834 | if (!hasOwn(obj, key)) {
|
2835 | continue;
|
2836 | }
|
2837 |
|
2838 | if (!key.includes('.')) {
|
2839 |
|
2840 | if (isObject(obj[key])) {
|
2841 | handleFlatJson(obj[key]);
|
2842 | }
|
2843 | }
|
2844 |
|
2845 | else {
|
2846 |
|
2847 | const subKeys = key.split('.');
|
2848 | const lastIndex = subKeys.length - 1;
|
2849 | let currentObj = obj;
|
2850 | for (let i = 0; i < lastIndex; i++) {
|
2851 | if (!(subKeys[i] in currentObj)) {
|
2852 | currentObj[subKeys[i]] = {};
|
2853 | }
|
2854 | currentObj = currentObj[subKeys[i]];
|
2855 | }
|
2856 |
|
2857 | currentObj[subKeys[lastIndex]] = obj[key];
|
2858 | delete obj[key];
|
2859 |
|
2860 | if (isObject(currentObj[subKeys[lastIndex]])) {
|
2861 | handleFlatJson(currentObj[subKeys[lastIndex]]);
|
2862 | }
|
2863 | }
|
2864 | }
|
2865 | return obj;
|
2866 | }
|
2867 | function getLocaleMessages(locale, options) {
|
2868 | const { messages, __i18n, messageResolver, flatJson } = options;
|
2869 |
|
2870 | const ret = isPlainObject(messages)
|
2871 | ? messages
|
2872 | : isArray(__i18n)
|
2873 | ? {}
|
2874 | : { [locale]: {} };
|
2875 |
|
2876 | if (isArray(__i18n)) {
|
2877 | __i18n.forEach(({ locale, resource }) => {
|
2878 | if (locale) {
|
2879 | ret[locale] = ret[locale] || {};
|
2880 | deepCopy(resource, ret[locale]);
|
2881 | }
|
2882 | else {
|
2883 | deepCopy(resource, ret);
|
2884 | }
|
2885 | });
|
2886 | }
|
2887 |
|
2888 | if (messageResolver == null && flatJson) {
|
2889 | for (const key in ret) {
|
2890 | if (hasOwn(ret, key)) {
|
2891 | handleFlatJson(ret[key]);
|
2892 | }
|
2893 | }
|
2894 | }
|
2895 | return ret;
|
2896 | }
|
2897 | const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
|
2898 |
|
2899 | function deepCopy(src, des) {
|
2900 |
|
2901 | if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
|
2902 | throw createI18nError(I18nErrorCodes.INVALID_VALUE);
|
2903 | }
|
2904 | for (const key in src) {
|
2905 | if (hasOwn(src, key)) {
|
2906 | if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
|
2907 |
|
2908 |
|
2909 |
|
2910 | des[key] = src[key];
|
2911 | }
|
2912 | else {
|
2913 |
|
2914 | deepCopy(src[key], des[key]);
|
2915 | }
|
2916 | }
|
2917 | }
|
2918 | }
|
2919 |
|
2920 |
|
2921 |
|
2922 | const DEVTOOLS_META = '__INTLIFY_META__';
|
2923 | let composerID = 0;
|
2924 | function defineCoreMissingHandler(missing) {
|
2925 | return ((ctx, locale, key, type) => {
|
2926 | return missing(locale, key, compositionApi.getCurrentInstance() || undefined, type);
|
2927 | });
|
2928 | }
|
2929 |
|
2930 | const getMetaInfo = () => {
|
2931 | const instance = compositionApi.getCurrentInstance();
|
2932 | return instance && instance.type[DEVTOOLS_META]
|
2933 | ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] }
|
2934 | : null;
|
2935 | };
|
2936 | |
2937 |
|
2938 |
|
2939 |
|
2940 |
|
2941 |
|
2942 | function createComposer(options = {}, VueI18nLegacy) {
|
2943 | const { __root } = options;
|
2944 | const _isGlobal = __root === undefined;
|
2945 | let _inheritLocale = isBoolean(options.inheritLocale)
|
2946 | ? options.inheritLocale
|
2947 | : true;
|
2948 | const _locale = compositionApi.ref(
|
2949 |
|
2950 | __root && _inheritLocale
|
2951 | ? __root.locale.value
|
2952 | : isString(options.locale)
|
2953 | ? options.locale
|
2954 | : DEFAULT_LOCALE);
|
2955 | const _fallbackLocale = compositionApi.ref(
|
2956 |
|
2957 | __root && _inheritLocale
|
2958 | ? __root.fallbackLocale.value
|
2959 | : isString(options.fallbackLocale) ||
|
2960 | isArray(options.fallbackLocale) ||
|
2961 | isPlainObject(options.fallbackLocale) ||
|
2962 | options.fallbackLocale === false
|
2963 | ? options.fallbackLocale
|
2964 | : _locale.value);
|
2965 | const _messages = compositionApi.ref(getLocaleMessages(_locale.value, options));
|
2966 |
|
2967 | const _datetimeFormats = compositionApi.ref(isPlainObject(options.datetimeFormats)
|
2968 | ? options.datetimeFormats
|
2969 | : { [_locale.value]: {} })
|
2970 | ;
|
2971 |
|
2972 | const _numberFormats = compositionApi.ref(isPlainObject(options.numberFormats)
|
2973 | ? options.numberFormats
|
2974 | : { [_locale.value]: {} })
|
2975 | ;
|
2976 |
|
2977 |
|
2978 | let _missingWarn = __root
|
2979 | ? __root.missingWarn
|
2980 | : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
|
2981 | ? options.missingWarn
|
2982 | : true;
|
2983 |
|
2984 | let _fallbackWarn = __root
|
2985 | ? __root.fallbackWarn
|
2986 | : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
|
2987 | ? options.fallbackWarn
|
2988 | : true;
|
2989 |
|
2990 | let _fallbackRoot = __root
|
2991 | ? __root.fallbackRoot
|
2992 | : isBoolean(options.fallbackRoot)
|
2993 | ? options.fallbackRoot
|
2994 | : true;
|
2995 |
|
2996 | let _fallbackFormat = !!options.fallbackFormat;
|
2997 |
|
2998 | let _missing = isFunction(options.missing) ? options.missing : null;
|
2999 | let _runtimeMissing = isFunction(options.missing)
|
3000 | ? defineCoreMissingHandler(options.missing)
|
3001 | : null;
|
3002 |
|
3003 | let _postTranslation = isFunction(options.postTranslation)
|
3004 | ? options.postTranslation
|
3005 | : null;
|
3006 | let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
|
3007 | ? options.warnHtmlMessage
|
3008 | : true;
|
3009 | let _escapeParameter = !!options.escapeParameter;
|
3010 |
|
3011 |
|
3012 | const _modifiers = __root
|
3013 | ? __root.modifiers
|
3014 | : isPlainObject(options.modifiers)
|
3015 | ? options.modifiers
|
3016 | : {};
|
3017 |
|
3018 | let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
|
3019 |
|
3020 | let __legacy;
|
3021 | {
|
3022 | if (!isLegacyVueI18n(VueI18nLegacy)) {
|
3023 | createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
|
3024 | }
|
3025 | const legacyOptions = {
|
3026 | locale: _locale.value,
|
3027 | fallbackLocale: _fallbackLocale.value,
|
3028 | messages: _messages.value,
|
3029 | dateTimeFormats: _datetimeFormats.value,
|
3030 | numberFormats: _numberFormats.value,
|
3031 | modifiers: _modifiers,
|
3032 | missing: _missing,
|
3033 | fallbackRoot: _fallbackRoot,
|
3034 | postTranslation: _postTranslation,
|
3035 | pluralizationRules: _pluralRules,
|
3036 | escapeParameterHtml: _escapeParameter,
|
3037 | sync: _inheritLocale,
|
3038 | silentFallbackWarn: isBoolean(_fallbackWarn)
|
3039 | ? !_fallbackWarn
|
3040 | : _fallbackWarn,
|
3041 | silentTranslationWarn: isBoolean(_missingWarn)
|
3042 | ? !_missingWarn
|
3043 | : _missingWarn,
|
3044 | formatFallbackMessages: isBoolean(_fallbackFormat)
|
3045 | ? !_fallbackFormat
|
3046 | : _fallbackFormat,
|
3047 | warnHtmlInMessage: isBoolean(_warnHtmlMessage)
|
3048 | ? _warnHtmlMessage
|
3049 | ? 'warn'
|
3050 | : 'off'
|
3051 | : 'off'
|
3052 | };
|
3053 | __legacy = new VueI18nLegacy(legacyOptions);
|
3054 | }
|
3055 |
|
3056 |
|
3057 | let _context;
|
3058 | function getCoreContext() {
|
3059 | const ctxOptions = {
|
3060 | version: VERSION,
|
3061 | locale: _locale.value,
|
3062 | fallbackLocale: _fallbackLocale.value,
|
3063 | messages: _messages.value,
|
3064 | modifiers: _modifiers,
|
3065 | pluralRules: _pluralRules,
|
3066 | missing: _runtimeMissing === null ? undefined : _runtimeMissing,
|
3067 | missingWarn: _missingWarn,
|
3068 | fallbackWarn: _fallbackWarn,
|
3069 | fallbackFormat: _fallbackFormat,
|
3070 | unresolving: true,
|
3071 | postTranslation: _postTranslation === null ? undefined : _postTranslation,
|
3072 | warnHtmlMessage: _warnHtmlMessage,
|
3073 | escapeParameter: _escapeParameter,
|
3074 | messageResolver: options.messageResolver,
|
3075 | __meta: { framework: 'vue' }
|
3076 | };
|
3077 | {
|
3078 | ctxOptions.datetimeFormats = _datetimeFormats.value;
|
3079 | ctxOptions.numberFormats = _numberFormats.value;
|
3080 | ctxOptions.__datetimeFormatters = isPlainObject(_context)
|
3081 | ? _context.__datetimeFormatters
|
3082 | : undefined;
|
3083 | ctxOptions.__numberFormatters = isPlainObject(_context)
|
3084 | ? _context.__numberFormatters
|
3085 | : undefined;
|
3086 | }
|
3087 | return createCoreContext(ctxOptions);
|
3088 | }
|
3089 | _context = getCoreContext();
|
3090 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3091 |
|
3092 | function trackReactivityValues() {
|
3093 | return [
|
3094 | _locale.value,
|
3095 | _fallbackLocale.value,
|
3096 | _messages.value,
|
3097 | _datetimeFormats.value,
|
3098 | _numberFormats.value
|
3099 | ]
|
3100 | ;
|
3101 | }
|
3102 |
|
3103 | const locale = compositionApi.computed({
|
3104 | get: () => _locale.value,
|
3105 | set: val => {
|
3106 | _locale.value = val;
|
3107 | {
|
3108 | if (__legacy) {
|
3109 | __legacy.locale = val;
|
3110 | }
|
3111 | }
|
3112 | _context.locale = _locale.value;
|
3113 | }
|
3114 | });
|
3115 |
|
3116 | const fallbackLocale = compositionApi.computed({
|
3117 | get: () => _fallbackLocale.value,
|
3118 | set: val => {
|
3119 | _fallbackLocale.value = val;
|
3120 | {
|
3121 | if (__legacy) {
|
3122 | __legacy.fallbackLocale = val;
|
3123 | }
|
3124 | }
|
3125 | _context.fallbackLocale = _fallbackLocale.value;
|
3126 | updateFallbackLocale(_context, _locale.value, val);
|
3127 | }
|
3128 | });
|
3129 |
|
3130 | const messages = compositionApi.computed(() => _messages.value);
|
3131 |
|
3132 | const datetimeFormats = compositionApi.computed(() => _datetimeFormats.value);
|
3133 |
|
3134 | const numberFormats = compositionApi.computed(() => _numberFormats.value);
|
3135 |
|
3136 | function getPostTranslationHandler() {
|
3137 | return isFunction(_postTranslation) ? _postTranslation : null;
|
3138 | }
|
3139 |
|
3140 | function setPostTranslationHandler(handler) {
|
3141 | _postTranslation = handler;
|
3142 | _context.postTranslation = handler;
|
3143 | }
|
3144 |
|
3145 | function getMissingHandler() {
|
3146 | return _missing;
|
3147 | }
|
3148 |
|
3149 | function setMissingHandler(handler) {
|
3150 | if (handler !== null) {
|
3151 | _runtimeMissing = defineCoreMissingHandler(handler);
|
3152 | }
|
3153 | _missing = handler;
|
3154 | _context.missing = _runtimeMissing;
|
3155 | }
|
3156 | function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
|
3157 | ) {
|
3158 | return type !== 'translate' || !arg.resolvedMessage;
|
3159 | }
|
3160 | function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
|
3161 | trackReactivityValues();
|
3162 |
|
3163 | let ret;
|
3164 | {
|
3165 | try {
|
3166 | setAdditionalMeta(getMetaInfo());
|
3167 | ret = fn(_context);
|
3168 | }
|
3169 | finally {
|
3170 | setAdditionalMeta(null);
|
3171 | }
|
3172 | }
|
3173 | if (isNumber(ret) && ret === NOT_REOSLVED) {
|
3174 | const [key, arg2] = argumentParser();
|
3175 | if (__root &&
|
3176 | isString(key) &&
|
3177 | isResolvedTranslateMessage(warnType, arg2)) {
|
3178 | if (_fallbackRoot &&
|
3179 | (isTranslateFallbackWarn(_fallbackWarn, key) ||
|
3180 | isTranslateMissingWarn(_missingWarn, key))) {
|
3181 | warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
|
3182 | key,
|
3183 | type: warnType
|
3184 | }));
|
3185 | }
|
3186 | }
|
3187 | return __root && _fallbackRoot
|
3188 | ? fallbackSuccess(__root)
|
3189 | : fallbackFail(key);
|
3190 | }
|
3191 | else if (successCondition(ret)) {
|
3192 | return ret;
|
3193 | }
|
3194 | else {
|
3195 |
|
3196 | throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
|
3197 | }
|
3198 | }
|
3199 |
|
3200 | function t(...args) {
|
3201 | return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
|
3202 | }
|
3203 |
|
3204 | function rt(...args) {
|
3205 | const [arg1, arg2, arg3] = args;
|
3206 | if (arg3 && !isObject(arg3)) {
|
3207 | throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
|
3208 | }
|
3209 | return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
|
3210 | }
|
3211 |
|
3212 | function d(...args) {
|
3213 | return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
|
3214 | }
|
3215 |
|
3216 | function n(...args) {
|
3217 | return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
|
3218 | }
|
3219 | function setPluralRules(rules) {
|
3220 | _pluralRules = rules;
|
3221 | _context.pluralRules = _pluralRules;
|
3222 | }
|
3223 |
|
3224 | function te(key, locale) {
|
3225 | const targetLocale = isString(locale) ? locale : _locale.value;
|
3226 | const message = getLocaleMessage(targetLocale);
|
3227 | return _context.messageResolver(message, key) !== null;
|
3228 | }
|
3229 | function resolveMessages(key) {
|
3230 | let messages = null;
|
3231 | const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
|
3232 | for (let i = 0; i < locales.length; i++) {
|
3233 | const targetLocaleMessages = _messages.value[locales[i]] || {};
|
3234 | const messageValue = _context.messageResolver(targetLocaleMessages, key);
|
3235 | if (messageValue != null) {
|
3236 | messages = messageValue;
|
3237 | break;
|
3238 | }
|
3239 | }
|
3240 | return messages;
|
3241 | }
|
3242 |
|
3243 | function tm(key) {
|
3244 | const messages = resolveMessages(key);
|
3245 |
|
3246 | return messages != null
|
3247 | ? messages
|
3248 | : __root
|
3249 | ? __root.tm(key) || {}
|
3250 | : {};
|
3251 | }
|
3252 |
|
3253 | function getLocaleMessage(locale) {
|
3254 | return (_messages.value[locale] || {});
|
3255 | }
|
3256 |
|
3257 | function setLocaleMessage(locale, message) {
|
3258 | _messages.value[locale] = message;
|
3259 | {
|
3260 | __legacy && __legacy.setLocaleMessage(locale, message);
|
3261 | }
|
3262 | _context.messages = _messages.value;
|
3263 | }
|
3264 |
|
3265 | function mergeLocaleMessage(locale, message) {
|
3266 | _messages.value[locale] = _messages.value[locale] || {};
|
3267 | {
|
3268 | __legacy && __legacy.mergeLocaleMessage(locale, message);
|
3269 | }
|
3270 | deepCopy(message, _messages.value[locale]);
|
3271 | _context.messages = _messages.value;
|
3272 | }
|
3273 |
|
3274 | function getDateTimeFormat(locale) {
|
3275 | return _datetimeFormats.value[locale] || {};
|
3276 | }
|
3277 |
|
3278 | function setDateTimeFormat(locale, format) {
|
3279 | _datetimeFormats.value[locale] = format;
|
3280 | {
|
3281 | __legacy && __legacy.setDateTimeFormat(locale, format);
|
3282 | }
|
3283 | _context.datetimeFormats = _datetimeFormats.value;
|
3284 | clearDateTimeFormat(_context, locale, format);
|
3285 | }
|
3286 |
|
3287 | function mergeDateTimeFormat(locale, format) {
|
3288 | _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
|
3289 | {
|
3290 | __legacy && __legacy.mergeDateTimeFormat(locale, format);
|
3291 | }
|
3292 | _context.datetimeFormats = _datetimeFormats.value;
|
3293 | clearDateTimeFormat(_context, locale, format);
|
3294 | }
|
3295 |
|
3296 | function getNumberFormat(locale) {
|
3297 | return _numberFormats.value[locale] || {};
|
3298 | }
|
3299 |
|
3300 | function setNumberFormat(locale, format) {
|
3301 | _numberFormats.value[locale] = format;
|
3302 | {
|
3303 | __legacy && __legacy.setNumberFormat(locale, format);
|
3304 | }
|
3305 | _context.numberFormats = _numberFormats.value;
|
3306 | clearNumberFormat(_context, locale, format);
|
3307 | }
|
3308 |
|
3309 | function mergeNumberFormat(locale, format) {
|
3310 | _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
|
3311 | {
|
3312 | __legacy && __legacy.mergeNumberFormat(locale, format);
|
3313 | }
|
3314 | _context.numberFormats = _numberFormats.value;
|
3315 | clearNumberFormat(_context, locale, format);
|
3316 | }
|
3317 |
|
3318 | composerID++;
|
3319 |
|
3320 | if (__root) {
|
3321 | compositionApi.watch(__root.locale, (val) => {
|
3322 | if (_inheritLocale) {
|
3323 | _locale.value = val;
|
3324 | {
|
3325 | if (__legacy) {
|
3326 | __legacy.locale = val;
|
3327 | }
|
3328 | }
|
3329 | _context.locale = val;
|
3330 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3331 | }
|
3332 | });
|
3333 | compositionApi.watch(__root.fallbackLocale, (val) => {
|
3334 | if (_inheritLocale) {
|
3335 | _fallbackLocale.value = val;
|
3336 | {
|
3337 | if (__legacy) {
|
3338 | __legacy.fallbackLocale = val;
|
3339 | }
|
3340 | }
|
3341 | _context.fallbackLocale = val;
|
3342 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3343 | }
|
3344 | });
|
3345 | }
|
3346 |
|
3347 | const composer = {
|
3348 | id: composerID,
|
3349 | locale,
|
3350 | fallbackLocale,
|
3351 | get inheritLocale() {
|
3352 | return _inheritLocale;
|
3353 | },
|
3354 | set inheritLocale(val) {
|
3355 | _inheritLocale = val;
|
3356 | {
|
3357 | if (__legacy) {
|
3358 | __legacy._sync = val;
|
3359 | }
|
3360 | }
|
3361 | if (val && __root) {
|
3362 | _locale.value = __root.locale.value;
|
3363 | _fallbackLocale.value = __root.fallbackLocale.value;
|
3364 | {
|
3365 | if (__legacy) {
|
3366 | __legacy.locale = __root.locale.value;
|
3367 | __legacy.fallbackLocale = __root.fallbackLocale.value;
|
3368 | }
|
3369 | }
|
3370 | updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
|
3371 | }
|
3372 | },
|
3373 | get availableLocales() {
|
3374 | return Object.keys(_messages.value).sort();
|
3375 | },
|
3376 | messages,
|
3377 | get modifiers() {
|
3378 | return _modifiers;
|
3379 | },
|
3380 | get pluralRules() {
|
3381 | return _pluralRules || {};
|
3382 | },
|
3383 | get isGlobal() {
|
3384 | return _isGlobal;
|
3385 | },
|
3386 | get missingWarn() {
|
3387 | return _missingWarn;
|
3388 | },
|
3389 | set missingWarn(val) {
|
3390 | _missingWarn = val;
|
3391 | _context.missingWarn = _missingWarn;
|
3392 | },
|
3393 | get fallbackWarn() {
|
3394 | return _fallbackWarn;
|
3395 | },
|
3396 | set fallbackWarn(val) {
|
3397 | _fallbackWarn = val;
|
3398 | _context.fallbackWarn = _fallbackWarn;
|
3399 | },
|
3400 | get fallbackRoot() {
|
3401 | return _fallbackRoot;
|
3402 | },
|
3403 | set fallbackRoot(val) {
|
3404 | _fallbackRoot = val;
|
3405 | },
|
3406 | get fallbackFormat() {
|
3407 | return _fallbackFormat;
|
3408 | },
|
3409 | set fallbackFormat(val) {
|
3410 | _fallbackFormat = val;
|
3411 | _context.fallbackFormat = _fallbackFormat;
|
3412 | },
|
3413 | get warnHtmlMessage() {
|
3414 | return _warnHtmlMessage;
|
3415 | },
|
3416 | set warnHtmlMessage(val) {
|
3417 | _warnHtmlMessage = val;
|
3418 | _context.warnHtmlMessage = val;
|
3419 | },
|
3420 | get escapeParameter() {
|
3421 | return _escapeParameter;
|
3422 | },
|
3423 | set escapeParameter(val) {
|
3424 | _escapeParameter = val;
|
3425 | _context.escapeParameter = val;
|
3426 | },
|
3427 | t,
|
3428 | getLocaleMessage,
|
3429 | setLocaleMessage,
|
3430 | mergeLocaleMessage,
|
3431 | getPostTranslationHandler,
|
3432 | setPostTranslationHandler,
|
3433 | getMissingHandler,
|
3434 | setMissingHandler,
|
3435 | [SetPluralRulesSymbol]: setPluralRules
|
3436 | };
|
3437 | {
|
3438 | composer.datetimeFormats = datetimeFormats;
|
3439 | composer.numberFormats = numberFormats;
|
3440 | composer.rt = rt;
|
3441 | composer.te = te;
|
3442 | composer.tm = tm;
|
3443 | composer.d = d;
|
3444 | composer.n = n;
|
3445 | composer.getDateTimeFormat = getDateTimeFormat;
|
3446 | composer.setDateTimeFormat = setDateTimeFormat;
|
3447 | composer.mergeDateTimeFormat = mergeDateTimeFormat;
|
3448 | composer.getNumberFormat = getNumberFormat;
|
3449 | composer.setNumberFormat = setNumberFormat;
|
3450 | composer.mergeNumberFormat = mergeNumberFormat;
|
3451 | }
|
3452 | {
|
3453 | composer[LegacyInstanceSymbol] = __legacy;
|
3454 | }
|
3455 | return composer;
|
3456 | }
|
3457 |
|
3458 |
|
3459 | |
3460 |
|
3461 |
|
3462 |
|
3463 | function defineMixin(i18n, VueI18n // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
|
3464 | ) {
|
3465 | return {
|
3466 | beforeCreate() {
|
3467 | const options = this.$options;
|
3468 | if (options.__VUE18N__INSTANCE__) {
|
3469 | return;
|
3470 | }
|
3471 | options.i18n = options.i18n || (options.__i18n ? {} : null);
|
3472 | this._i18nBridgeRoot = i18n;
|
3473 | if (i18n.mode === 'composition') {
|
3474 | this._i18n = i18n;
|
3475 | return;
|
3476 | }
|
3477 | if (options.i18n) {
|
3478 | if (options.i18n instanceof VueI18n) {
|
3479 |
|
3480 | if (options.__i18n) {
|
3481 | try {
|
3482 | const localeMessages = options.i18n && options.i18n.messages
|
3483 | ? options.i18n.messages
|
3484 | : {};
|
3485 | options.__i18n.forEach(resource => deepCopy(localeMessages, JSON.parse(resource)));
|
3486 | Object.keys(localeMessages).forEach((locale) => {
|
3487 | options.i18n.mergeLocaleMessage(locale, localeMessages[locale]);
|
3488 | });
|
3489 | }
|
3490 | catch (e) {
|
3491 | {
|
3492 | console.error(`Cannot parse locale messages via custom blocks.`, e);
|
3493 | }
|
3494 | }
|
3495 | }
|
3496 | this._i18n = options.i18n;
|
3497 | this._i18nWatcher = this._i18n.watchI18nData();
|
3498 | }
|
3499 | else if (isPlainObject(options.i18n)) {
|
3500 | const rootI18n = this.$root &&
|
3501 | this.$root.$i18n &&
|
3502 | this.$root.$i18n instanceof VueI18n
|
3503 | ? this.$root.$i18n
|
3504 | : null;
|
3505 |
|
3506 | if (rootI18n) {
|
3507 | options.i18n.root = this.$root;
|
3508 | options.i18n.formatter = rootI18n.formatter;
|
3509 | options.i18n.fallbackLocale = rootI18n.fallbackLocale;
|
3510 | options.i18n.formatFallbackMessages =
|
3511 | rootI18n.formatFallbackMessages;
|
3512 | options.i18n.silentTranslationWarn = rootI18n.silentTranslationWarn;
|
3513 | options.i18n.silentFallbackWarn = rootI18n.silentFallbackWarn;
|
3514 | options.i18n.pluralizationRules = rootI18n.pluralizationRules;
|
3515 | options.i18n.preserveDirectiveContent =
|
3516 | rootI18n.preserveDirectiveContent;
|
3517 | }
|
3518 |
|
3519 | if (options.__i18n) {
|
3520 | try {
|
3521 | const localeMessages = options.i18n && options.i18n.messages
|
3522 | ? options.i18n.messages
|
3523 | : {};
|
3524 | options.__i18n.forEach(resource => deepCopy(localeMessages, JSON.parse(resource)));
|
3525 | options.i18n.messages = localeMessages;
|
3526 | }
|
3527 | catch (e) {
|
3528 | {
|
3529 | warn(`Cannot parse locale messages via custom blocks.`, e);
|
3530 | }
|
3531 | }
|
3532 | }
|
3533 | const { sharedMessages } = options.i18n;
|
3534 | if (sharedMessages && isPlainObject(sharedMessages)) {
|
3535 | deepCopy(options.i18n.messages, sharedMessages);
|
3536 | }
|
3537 | this._i18n = new VueI18n(options.i18n);
|
3538 | this._i18nWatcher = this._i18n.watchI18nData();
|
3539 | if (options.i18n.sync === undefined || !!options.i18n.sync) {
|
3540 | this._localeWatcher = this.$i18n.watchLocale();
|
3541 | }
|
3542 | if (rootI18n) {
|
3543 | rootI18n.onComponentInstanceCreated(this._i18n);
|
3544 | }
|
3545 | }
|
3546 | else {
|
3547 | {
|
3548 | warn(`Cannot be interpreted 'i18n' option.`);
|
3549 | }
|
3550 | }
|
3551 | }
|
3552 | else if (this.$root &&
|
3553 | this.$root.$i18n &&
|
3554 | this.$root.$i18n instanceof VueI18n) {
|
3555 |
|
3556 | this._i18n = this.$root.$i18n;
|
3557 | }
|
3558 | else if (options.parent &&
|
3559 | options.parent.$i18n &&
|
3560 | options.parent.$i18n instanceof VueI18n) {
|
3561 |
|
3562 | this._i18n = options.parent.$i18n;
|
3563 | }
|
3564 | },
|
3565 | beforeMount() {
|
3566 | const options = this.$options;
|
3567 | if (options.__VUE18N__INSTANCE__) {
|
3568 | return;
|
3569 | }
|
3570 | options.i18n = options.i18n || (options.__i18n ? {} : null);
|
3571 | if (options.i18n) {
|
3572 | if (options.i18n instanceof VueI18n) {
|
3573 |
|
3574 | this._i18n.subscribeDataChanging(this);
|
3575 | this._subscribing = true;
|
3576 | }
|
3577 | else if (isPlainObject(options.i18n)) {
|
3578 | this._i18n.subscribeDataChanging(this);
|
3579 | this._subscribing = true;
|
3580 | }
|
3581 | else {
|
3582 | {
|
3583 | warn(`Cannot be interpreted 'i18n' option.`);
|
3584 | }
|
3585 | }
|
3586 | }
|
3587 | else if (this.$root &&
|
3588 | this.$root.$i18n &&
|
3589 | this.$root.$i18n instanceof VueI18n) {
|
3590 | this._i18n.subscribeDataChanging(this);
|
3591 | this._subscribing = true;
|
3592 | }
|
3593 | else if (options.parent &&
|
3594 | options.parent.$i18n &&
|
3595 | options.parent.$i18n instanceof VueI18n) {
|
3596 | this._i18n.subscribeDataChanging(this);
|
3597 | this._subscribing = true;
|
3598 | }
|
3599 | },
|
3600 | beforeDestroy() {
|
3601 | const options = this.$options;
|
3602 | if (options.__VUE18N__INSTANCE__) {
|
3603 | return;
|
3604 | }
|
3605 | if (this._i18nBridgeRoot) {
|
3606 | delete this._i18nBridgeRoot;
|
3607 | return;
|
3608 | }
|
3609 | if (i18n.mode === 'composition') {
|
3610 | delete this._i18n;
|
3611 | return;
|
3612 | }
|
3613 | if (!this._i18n) {
|
3614 | return;
|
3615 | }
|
3616 | const self = this;
|
3617 | this.$nextTick(() => {
|
3618 | if (self._subscribing) {
|
3619 | self._i18n.unsubscribeDataChanging(self);
|
3620 | delete self._subscribing;
|
3621 | }
|
3622 | if (self._i18nWatcher) {
|
3623 | self._i18nWatcher();
|
3624 | self._i18n.destroyVM();
|
3625 | delete self._i18nWatcher;
|
3626 | }
|
3627 | if (self._localeWatcher) {
|
3628 | self._localeWatcher();
|
3629 | delete self._localeWatcher;
|
3630 | }
|
3631 | });
|
3632 | }
|
3633 | };
|
3634 | }
|
3635 |
|
3636 |
|
3637 | let _legacyVueI18n = null;
|
3638 | let _legacyI18n = null;
|
3639 | |
3640 |
|
3641 |
|
3642 |
|
3643 |
|
3644 |
|
3645 |
|
3646 |
|
3647 |
|
3648 | const I18nInjectionKey =
|
3649 | makeSymbol('global-vue-i18n');
|
3650 |
|
3651 | function createI18n(options = {}, VueI18nLegacy) {
|
3652 | if (_legacyI18n) {
|
3653 | warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE));
|
3654 | return _legacyI18n;
|
3655 | }
|
3656 | {
|
3657 | _legacyVueI18n = VueI18nLegacy;
|
3658 | }
|
3659 |
|
3660 | const __legacyMode = isBoolean(options.legacy)
|
3661 | ? options.legacy
|
3662 | : true;
|
3663 | !!options.globalInjection;
|
3664 | const __instances = new Map();
|
3665 | const __global = createGlobal(options, __legacyMode, VueI18nLegacy);
|
3666 | function __getInstance(component) {
|
3667 | return __instances.get(component) || null;
|
3668 | }
|
3669 | function __setInstance(component, instance) {
|
3670 | __instances.set(component, instance);
|
3671 | }
|
3672 | function __deleteInstance(component) {
|
3673 | __instances.delete(component);
|
3674 | }
|
3675 | {
|
3676 |
|
3677 | const i18n = __global[LegacyInstanceSymbol];
|
3678 | Object.defineProperty(i18n, 'global', {
|
3679 | get() {
|
3680 | return __global;
|
3681 | }
|
3682 | });
|
3683 | Object.defineProperty(i18n, 'mode', {
|
3684 | get() {
|
3685 | return __legacyMode ? 'legacy' : 'composition';
|
3686 | }
|
3687 | });
|
3688 | Object.defineProperty(i18n, '__instances', {
|
3689 | get() {
|
3690 | return __instances;
|
3691 | }
|
3692 | });
|
3693 | Object.defineProperty(i18n, 'install', {
|
3694 |
|
3695 | value: (Vue) => {
|
3696 | const version = (Vue && Vue.version && Number(Vue.version.split('.')[0])) || -1;
|
3697 | if (version !== 2) {
|
3698 | throw createI18nError(I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY);
|
3699 | }
|
3700 | Vue.mixin(defineMixin(i18n, _legacyVueI18n));
|
3701 | }
|
3702 | });
|
3703 | const methodMap = {
|
3704 | __getInstance,
|
3705 | __setInstance,
|
3706 | __deleteInstance
|
3707 | };
|
3708 | Object.keys(methodMap).forEach(key => Object.defineProperty(i18n, key, { value: methodMap[key] })
|
3709 | );
|
3710 | _legacyI18n = i18n;
|
3711 | return i18n;
|
3712 | }
|
3713 | }
|
3714 |
|
3715 | function useI18n(options = {}) {
|
3716 | const instance = compositionApi.getCurrentInstance();
|
3717 | if (instance == null) {
|
3718 | throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
|
3719 | }
|
3720 | {
|
3721 | if (_legacyVueI18n == null || _legacyI18n == null) {
|
3722 | throw createI18nError(I18nErrorCodes.NOT_INSLALLED);
|
3723 | }
|
3724 | }
|
3725 | const i18n = getI18nInstance(instance);
|
3726 | const global = getGlobalComposer(i18n);
|
3727 | const componentOptions = getComponentOptions(instance);
|
3728 | const scope = getScope(options, componentOptions);
|
3729 | if (scope === 'global') {
|
3730 | adjustI18nResources(global, options, componentOptions);
|
3731 | return global;
|
3732 | }
|
3733 | if (scope === 'parent') {
|
3734 | let composer = getComposer(i18n, instance);
|
3735 | if (composer == null) {
|
3736 | {
|
3737 | warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
|
3738 | }
|
3739 | composer = global;
|
3740 | }
|
3741 | return composer;
|
3742 | }
|
3743 |
|
3744 | if (i18n.mode === 'legacy') {
|
3745 | throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
|
3746 | }
|
3747 | const i18nInternal = i18n;
|
3748 | let composer = i18nInternal.__getInstance(instance);
|
3749 | if (composer == null) {
|
3750 | const composerOptions = assign({}, options);
|
3751 | if ('__i18n' in componentOptions) {
|
3752 | composerOptions.__i18n = componentOptions.__i18n;
|
3753 | }
|
3754 | if (global) {
|
3755 | composerOptions.__root = global;
|
3756 | }
|
3757 | composer = createComposer(composerOptions, _legacyVueI18n);
|
3758 | setupLifeCycle(i18nInternal, instance, composer);
|
3759 | i18nInternal.__setInstance(instance, composer);
|
3760 | }
|
3761 | return composer;
|
3762 | }
|
3763 | function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
|
3764 | ) {
|
3765 | {
|
3766 | if (!isLegacyVueI18n(VueI18nLegacy)) {
|
3767 | throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
|
3768 | }
|
3769 | return createComposer(options, VueI18nLegacy);
|
3770 | }
|
3771 | }
|
3772 | function getI18nInstance(instance) {
|
3773 | {
|
3774 | const vm = instance.proxy;
|
3775 |
|
3776 | if (vm == null) {
|
3777 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3778 | }
|
3779 | const i18n = vm._i18nBridgeRoot;
|
3780 |
|
3781 | if (!i18n) {
|
3782 | throw createI18nError(I18nErrorCodes.NOT_INSLALLED);
|
3783 | }
|
3784 | return i18n;
|
3785 | }
|
3786 | }
|
3787 |
|
3788 | function getComponentOptions(instance) {
|
3789 | return instance.proxy.$options;
|
3790 | }
|
3791 |
|
3792 | function getScope(options, componentOptions) {
|
3793 |
|
3794 | return isEmptyObject(options)
|
3795 | ? ('__i18n' in componentOptions)
|
3796 | ? 'local'
|
3797 | : 'global'
|
3798 | : !options.useScope
|
3799 | ? 'local'
|
3800 | : options.useScope;
|
3801 | }
|
3802 | function getGlobalComposer(i18n) {
|
3803 |
|
3804 | return i18n.global;
|
3805 | }
|
3806 | function adjustI18nResources(global, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
|
3807 | ) {
|
3808 | let messages = isObject(options.messages) ? options.messages : {};
|
3809 | if ('__i18nGlobal' in componentOptions) {
|
3810 | messages = getLocaleMessages(global.locale.value, {
|
3811 | messages,
|
3812 | __i18n: componentOptions.__i18nGlobal
|
3813 | });
|
3814 | }
|
3815 |
|
3816 | const locales = Object.keys(messages);
|
3817 | if (locales.length) {
|
3818 | locales.forEach(locale => {
|
3819 | global.mergeLocaleMessage(locale, messages[locale]);
|
3820 | });
|
3821 | }
|
3822 | {
|
3823 |
|
3824 | if (isObject(options.datetimeFormats)) {
|
3825 | const locales = Object.keys(options.datetimeFormats);
|
3826 | if (locales.length) {
|
3827 | locales.forEach(locale => {
|
3828 | global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
|
3829 | });
|
3830 | }
|
3831 | }
|
3832 |
|
3833 | if (isObject(options.numberFormats)) {
|
3834 | const locales = Object.keys(options.numberFormats);
|
3835 | if (locales.length) {
|
3836 | locales.forEach(locale => {
|
3837 | global.mergeNumberFormat(locale, options.numberFormats[locale]);
|
3838 | });
|
3839 | }
|
3840 | }
|
3841 | }
|
3842 | }
|
3843 | function getComposer(i18n, target) {
|
3844 | let composer = null;
|
3845 | const root = target.root;
|
3846 | let current = target.parent;
|
3847 | while (current != null) {
|
3848 | const i18nInternal = i18n;
|
3849 | if (i18n.mode === 'composition') {
|
3850 | composer = i18nInternal.__getInstance(current);
|
3851 | }
|
3852 | else {
|
3853 | {
|
3854 | const vueI18n = i18nInternal.__getInstance(current);
|
3855 | if (vueI18n != null) {
|
3856 | composer = vueI18n
|
3857 | .__composer;
|
3858 | }
|
3859 | }
|
3860 | }
|
3861 | if (composer != null) {
|
3862 | break;
|
3863 | }
|
3864 | if (root === current) {
|
3865 | break;
|
3866 | }
|
3867 | current = current.parent;
|
3868 | }
|
3869 | return composer;
|
3870 | }
|
3871 | function setupLifeCycle(i18n, target, composer) {
|
3872 | {
|
3873 |
|
3874 |
|
3875 | const vm = target.proxy;
|
3876 | if (vm == null) {
|
3877 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3878 | }
|
3879 |
|
3880 | const _i18n = composer[LegacyInstanceSymbol];
|
3881 | if (_i18n === i18n) {
|
3882 | throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
|
3883 | }
|
3884 | vm._i18n = _i18n;
|
3885 | vm._i18n_bridge = true;
|
3886 | vm._i18nWatcher = vm._i18n.watchI18nData();
|
3887 | if (vm._i18n._sync) {
|
3888 | vm._localeWatcher = vm._i18n.watchLocale();
|
3889 | }
|
3890 | let subscribing = false;
|
3891 | compositionApi.onBeforeMount(() => {
|
3892 | vm._i18n.subscribeDataChanging(vm);
|
3893 | subscribing = true;
|
3894 | }, target);
|
3895 | compositionApi.onUnmounted(() => {
|
3896 | if (subscribing) {
|
3897 | vm._i18n.unsubscribeDataChanging(vm);
|
3898 | subscribing = false;
|
3899 | }
|
3900 | if (vm._i18nWatcher) {
|
3901 | vm._i18nWatcher();
|
3902 | vm._i18n.destroyVM();
|
3903 | delete vm._i18nWatcher;
|
3904 | }
|
3905 | if (vm._localeWatcher) {
|
3906 | vm._localeWatcher();
|
3907 | delete vm._localeWatcher;
|
3908 | }
|
3909 | delete vm._i18n_bridge;
|
3910 | delete vm._i18n;
|
3911 | }, target);
|
3912 | }
|
3913 | }
|
3914 |
|
3915 |
|
3916 | registerMessageCompiler(compileToFunction);
|
3917 |
|
3918 | registerMessageResolver(resolveValue);
|
3919 |
|
3920 | registerLocaleFallbacker(fallbackWithLocaleChain);
|
3921 |
|
3922 | {
|
3923 | const target = getGlobalThis();
|
3924 | target.__INTLIFY__ = true;
|
3925 | setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
|
3926 | }
|
3927 | {
|
3928 | initDev();
|
3929 | }
|
3930 |
|
3931 | exports.I18nInjectionKey = I18nInjectionKey;
|
3932 | exports.VERSION = VERSION;
|
3933 | exports.createI18n = createI18n;
|
3934 | exports.useI18n = useI18n;
|
3935 |
|
3936 | Object.defineProperty(exports, '__esModule', { value: true });
|
3937 |
|
3938 | return exports;
|
3939 |
|
3940 | }({}, VueCompositionAPI));
|