@intlify/message-compiler 11.1.2 → 12.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1570 +0,0 @@
1
- /*!
2
- * message-compiler v11.1.2
3
- * (c) 2025 kazuya kawaguchi
4
- * Released under the MIT License.
5
- */
6
- 'use strict';
7
-
8
- var shared = require('@intlify/shared');
9
- var sourceMapJs = require('source-map-js');
10
-
11
- const LOCATION_STUB = {
12
- start: { line: 1, column: 1, offset: 0 },
13
- end: { line: 1, column: 1, offset: 0 }
14
- };
15
- function createPosition(line, column, offset) {
16
- return { line, column, offset };
17
- }
18
- function createLocation(start, end, source) {
19
- const loc = { start, end };
20
- if (source != null) {
21
- loc.source = source;
22
- }
23
- return loc;
24
- }
25
-
26
- const CompileErrorCodes = {
27
- // tokenizer error codes
28
- EXPECTED_TOKEN: 1,
29
- INVALID_TOKEN_IN_PLACEHOLDER: 2,
30
- UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
31
- UNKNOWN_ESCAPE_SEQUENCE: 4,
32
- INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
33
- UNBALANCED_CLOSING_BRACE: 6,
34
- UNTERMINATED_CLOSING_BRACE: 7,
35
- EMPTY_PLACEHOLDER: 8,
36
- NOT_ALLOW_NEST_PLACEHOLDER: 9,
37
- INVALID_LINKED_FORMAT: 10,
38
- // parser error codes
39
- MUST_HAVE_MESSAGES_IN_PLURAL: 11,
40
- UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
41
- UNEXPECTED_EMPTY_LINKED_KEY: 13,
42
- UNEXPECTED_LEXICAL_ANALYSIS: 14,
43
- // generator error codes
44
- UNHANDLED_CODEGEN_NODE_TYPE: 15,
45
- // minifier error codes
46
- UNHANDLED_MINIFIER_NODE_TYPE: 16
47
- };
48
- // Special value for higher-order compilers to pick up the last code
49
- // to avoid collision of error codes.
50
- // This should always be kept as the last item.
51
- const COMPILE_ERROR_CODES_EXTEND_POINT = 17;
52
- /** @internal */
53
- const errorMessages = {
54
- // tokenizer error messages
55
- [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
56
- [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
57
- [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
58
- [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
59
- [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
60
- [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
61
- [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
62
- [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
63
- [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
64
- [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
65
- // parser error messages
66
- [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
67
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
68
- [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
69
- [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
70
- // generator error messages
71
- [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
72
- // minimizer error messages
73
- [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
74
- };
75
- function createCompileError(code, loc, options = {}) {
76
- const { domain, messages, args } = options;
77
- const msg = code;
78
- const error = new SyntaxError(String(msg));
79
- error.code = code;
80
- if (loc) {
81
- error.location = loc;
82
- }
83
- error.domain = domain;
84
- return error;
85
- }
86
- /** @internal */
87
- function defaultOnError(error) {
88
- throw error;
89
- }
90
-
91
- // eslint-disable-next-line no-useless-escape
92
- const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
93
- const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
94
-
95
- const CHAR_SP = ' ';
96
- const CHAR_CR = '\r';
97
- const CHAR_LF = '\n';
98
- const CHAR_LS = String.fromCharCode(0x2028);
99
- const CHAR_PS = String.fromCharCode(0x2029);
100
- function createScanner(str) {
101
- const _buf = str;
102
- let _index = 0;
103
- let _line = 1;
104
- let _column = 1;
105
- let _peekOffset = 0;
106
- const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
107
- const isLF = (index) => _buf[index] === CHAR_LF;
108
- const isPS = (index) => _buf[index] === CHAR_PS;
109
- const isLS = (index) => _buf[index] === CHAR_LS;
110
- const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
111
- const index = () => _index;
112
- const line = () => _line;
113
- const column = () => _column;
114
- const peekOffset = () => _peekOffset;
115
- const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
116
- const currentChar = () => charAt(_index);
117
- const currentPeek = () => charAt(_index + _peekOffset);
118
- function next() {
119
- _peekOffset = 0;
120
- if (isLineEnd(_index)) {
121
- _line++;
122
- _column = 0;
123
- }
124
- if (isCRLF(_index)) {
125
- _index++;
126
- }
127
- _index++;
128
- _column++;
129
- return _buf[_index];
130
- }
131
- function peek() {
132
- if (isCRLF(_index + _peekOffset)) {
133
- _peekOffset++;
134
- }
135
- _peekOffset++;
136
- return _buf[_index + _peekOffset];
137
- }
138
- function reset() {
139
- _index = 0;
140
- _line = 1;
141
- _column = 1;
142
- _peekOffset = 0;
143
- }
144
- function resetPeek(offset = 0) {
145
- _peekOffset = offset;
146
- }
147
- function skipToPeek() {
148
- const target = _index + _peekOffset;
149
- while (target !== _index) {
150
- next();
151
- }
152
- _peekOffset = 0;
153
- }
154
- return {
155
- index,
156
- line,
157
- column,
158
- peekOffset,
159
- charAt,
160
- currentChar,
161
- currentPeek,
162
- next,
163
- peek,
164
- reset,
165
- resetPeek,
166
- skipToPeek
167
- };
168
- }
169
-
170
- const EOF = undefined;
171
- const DOT = '.';
172
- const LITERAL_DELIMITER = "'";
173
- const ERROR_DOMAIN$1 = 'tokenizer';
174
- function createTokenizer(source, options = {}) {
175
- const location = options.location !== false;
176
- const _scnr = createScanner(source);
177
- const currentOffset = () => _scnr.index();
178
- const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
179
- const _initLoc = currentPosition();
180
- const _initOffset = currentOffset();
181
- const _context = {
182
- currentType: 13 /* TokenTypes.EOF */,
183
- offset: _initOffset,
184
- startLoc: _initLoc,
185
- endLoc: _initLoc,
186
- lastType: 13 /* TokenTypes.EOF */,
187
- lastOffset: _initOffset,
188
- lastStartLoc: _initLoc,
189
- lastEndLoc: _initLoc,
190
- braceNest: 0,
191
- inLinked: false,
192
- text: ''
193
- };
194
- const context = () => _context;
195
- const { onError } = options;
196
- function emitError(code, pos, offset, ...args) {
197
- const ctx = context();
198
- pos.column += offset;
199
- pos.offset += offset;
200
- if (onError) {
201
- const loc = location ? createLocation(ctx.startLoc, pos) : null;
202
- const err = createCompileError(code, loc, {
203
- domain: ERROR_DOMAIN$1,
204
- args
205
- });
206
- onError(err);
207
- }
208
- }
209
- function getToken(context, type, value) {
210
- context.endLoc = currentPosition();
211
- context.currentType = type;
212
- const token = { type };
213
- if (location) {
214
- token.loc = createLocation(context.startLoc, context.endLoc);
215
- }
216
- if (value != null) {
217
- token.value = value;
218
- }
219
- return token;
220
- }
221
- const getEndToken = (context) => getToken(context, 13 /* TokenTypes.EOF */);
222
- function eat(scnr, ch) {
223
- if (scnr.currentChar() === ch) {
224
- scnr.next();
225
- return ch;
226
- }
227
- else {
228
- emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
229
- return '';
230
- }
231
- }
232
- function peekSpaces(scnr) {
233
- let buf = '';
234
- while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
235
- buf += scnr.currentPeek();
236
- scnr.peek();
237
- }
238
- return buf;
239
- }
240
- function skipSpaces(scnr) {
241
- const buf = peekSpaces(scnr);
242
- scnr.skipToPeek();
243
- return buf;
244
- }
245
- function isIdentifierStart(ch) {
246
- if (ch === EOF) {
247
- return false;
248
- }
249
- const cc = ch.charCodeAt(0);
250
- return ((cc >= 97 && cc <= 122) || // a-z
251
- (cc >= 65 && cc <= 90) || // A-Z
252
- cc === 95 // _
253
- );
254
- }
255
- function isNumberStart(ch) {
256
- if (ch === EOF) {
257
- return false;
258
- }
259
- const cc = ch.charCodeAt(0);
260
- return cc >= 48 && cc <= 57; // 0-9
261
- }
262
- function isNamedIdentifierStart(scnr, context) {
263
- const { currentType } = context;
264
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
265
- return false;
266
- }
267
- peekSpaces(scnr);
268
- const ret = isIdentifierStart(scnr.currentPeek());
269
- scnr.resetPeek();
270
- return ret;
271
- }
272
- function isListIdentifierStart(scnr, context) {
273
- const { currentType } = context;
274
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
275
- return false;
276
- }
277
- peekSpaces(scnr);
278
- const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
279
- const ret = isNumberStart(ch);
280
- scnr.resetPeek();
281
- return ret;
282
- }
283
- function isLiteralStart(scnr, context) {
284
- const { currentType } = context;
285
- if (currentType !== 2 /* TokenTypes.BraceLeft */) {
286
- return false;
287
- }
288
- peekSpaces(scnr);
289
- const ret = scnr.currentPeek() === LITERAL_DELIMITER;
290
- scnr.resetPeek();
291
- return ret;
292
- }
293
- function isLinkedDotStart(scnr, context) {
294
- const { currentType } = context;
295
- if (currentType !== 7 /* TokenTypes.LinkedAlias */) {
296
- return false;
297
- }
298
- peekSpaces(scnr);
299
- const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
300
- scnr.resetPeek();
301
- return ret;
302
- }
303
- function isLinkedModifierStart(scnr, context) {
304
- const { currentType } = context;
305
- if (currentType !== 8 /* TokenTypes.LinkedDot */) {
306
- return false;
307
- }
308
- peekSpaces(scnr);
309
- const ret = isIdentifierStart(scnr.currentPeek());
310
- scnr.resetPeek();
311
- return ret;
312
- }
313
- function isLinkedDelimiterStart(scnr, context) {
314
- const { currentType } = context;
315
- if (!(currentType === 7 /* TokenTypes.LinkedAlias */ ||
316
- currentType === 11 /* TokenTypes.LinkedModifier */)) {
317
- return false;
318
- }
319
- peekSpaces(scnr);
320
- const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
321
- scnr.resetPeek();
322
- return ret;
323
- }
324
- function isLinkedReferStart(scnr, context) {
325
- const { currentType } = context;
326
- if (currentType !== 9 /* TokenTypes.LinkedDelimiter */) {
327
- return false;
328
- }
329
- const fn = () => {
330
- const ch = scnr.currentPeek();
331
- if (ch === "{" /* TokenChars.BraceLeft */) {
332
- return isIdentifierStart(scnr.peek());
333
- }
334
- else if (ch === "@" /* TokenChars.LinkedAlias */ ||
335
- ch === "|" /* TokenChars.Pipe */ ||
336
- ch === ":" /* TokenChars.LinkedDelimiter */ ||
337
- ch === "." /* TokenChars.LinkedDot */ ||
338
- ch === CHAR_SP ||
339
- !ch) {
340
- return false;
341
- }
342
- else if (ch === CHAR_LF) {
343
- scnr.peek();
344
- return fn();
345
- }
346
- else {
347
- // other characters
348
- return isTextStart(scnr, false);
349
- }
350
- };
351
- const ret = fn();
352
- scnr.resetPeek();
353
- return ret;
354
- }
355
- function isPluralStart(scnr) {
356
- peekSpaces(scnr);
357
- const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
358
- scnr.resetPeek();
359
- return ret;
360
- }
361
- function isTextStart(scnr, reset = true) {
362
- const fn = (hasSpace = false, prev = '') => {
363
- const ch = scnr.currentPeek();
364
- if (ch === "{" /* TokenChars.BraceLeft */) {
365
- return hasSpace;
366
- }
367
- else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
368
- return hasSpace;
369
- }
370
- else if (ch === "|" /* TokenChars.Pipe */) {
371
- return !(prev === CHAR_SP || prev === CHAR_LF);
372
- }
373
- else if (ch === CHAR_SP) {
374
- scnr.peek();
375
- return fn(true, CHAR_SP);
376
- }
377
- else if (ch === CHAR_LF) {
378
- scnr.peek();
379
- return fn(true, CHAR_LF);
380
- }
381
- else {
382
- return true;
383
- }
384
- };
385
- const ret = fn();
386
- reset && scnr.resetPeek();
387
- return ret;
388
- }
389
- function takeChar(scnr, fn) {
390
- const ch = scnr.currentChar();
391
- if (ch === EOF) {
392
- return EOF;
393
- }
394
- if (fn(ch)) {
395
- scnr.next();
396
- return ch;
397
- }
398
- return null;
399
- }
400
- function isIdentifier(ch) {
401
- const cc = ch.charCodeAt(0);
402
- return ((cc >= 97 && cc <= 122) || // a-z
403
- (cc >= 65 && cc <= 90) || // A-Z
404
- (cc >= 48 && cc <= 57) || // 0-9
405
- cc === 95 || // _
406
- cc === 36 // $
407
- );
408
- }
409
- function takeIdentifierChar(scnr) {
410
- return takeChar(scnr, isIdentifier);
411
- }
412
- function isNamedIdentifier(ch) {
413
- const cc = ch.charCodeAt(0);
414
- return ((cc >= 97 && cc <= 122) || // a-z
415
- (cc >= 65 && cc <= 90) || // A-Z
416
- (cc >= 48 && cc <= 57) || // 0-9
417
- cc === 95 || // _
418
- cc === 36 || // $
419
- cc === 45 // -
420
- );
421
- }
422
- function takeNamedIdentifierChar(scnr) {
423
- return takeChar(scnr, isNamedIdentifier);
424
- }
425
- function isDigit(ch) {
426
- const cc = ch.charCodeAt(0);
427
- return cc >= 48 && cc <= 57; // 0-9
428
- }
429
- function takeDigit(scnr) {
430
- return takeChar(scnr, isDigit);
431
- }
432
- function isHexDigit(ch) {
433
- const cc = ch.charCodeAt(0);
434
- return ((cc >= 48 && cc <= 57) || // 0-9
435
- (cc >= 65 && cc <= 70) || // A-F
436
- (cc >= 97 && cc <= 102)); // a-f
437
- }
438
- function takeHexDigit(scnr) {
439
- return takeChar(scnr, isHexDigit);
440
- }
441
- function getDigits(scnr) {
442
- let ch = '';
443
- let num = '';
444
- while ((ch = takeDigit(scnr))) {
445
- num += ch;
446
- }
447
- return num;
448
- }
449
- function readText(scnr) {
450
- let buf = '';
451
- while (true) {
452
- const ch = scnr.currentChar();
453
- if (ch === "{" /* TokenChars.BraceLeft */ ||
454
- ch === "}" /* TokenChars.BraceRight */ ||
455
- ch === "@" /* TokenChars.LinkedAlias */ ||
456
- ch === "|" /* TokenChars.Pipe */ ||
457
- !ch) {
458
- break;
459
- }
460
- else if (ch === CHAR_SP || ch === CHAR_LF) {
461
- if (isTextStart(scnr)) {
462
- buf += ch;
463
- scnr.next();
464
- }
465
- else if (isPluralStart(scnr)) {
466
- break;
467
- }
468
- else {
469
- buf += ch;
470
- scnr.next();
471
- }
472
- }
473
- else {
474
- buf += ch;
475
- scnr.next();
476
- }
477
- }
478
- return buf;
479
- }
480
- function readNamedIdentifier(scnr) {
481
- skipSpaces(scnr);
482
- let ch = '';
483
- let name = '';
484
- while ((ch = takeNamedIdentifierChar(scnr))) {
485
- name += ch;
486
- }
487
- if (scnr.currentChar() === EOF) {
488
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
489
- }
490
- return name;
491
- }
492
- function readListIdentifier(scnr) {
493
- skipSpaces(scnr);
494
- let value = '';
495
- if (scnr.currentChar() === '-') {
496
- scnr.next();
497
- value += `-${getDigits(scnr)}`;
498
- }
499
- else {
500
- value += getDigits(scnr);
501
- }
502
- if (scnr.currentChar() === EOF) {
503
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
504
- }
505
- return value;
506
- }
507
- function isLiteral(ch) {
508
- return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;
509
- }
510
- function readLiteral(scnr) {
511
- skipSpaces(scnr);
512
- // eslint-disable-next-line no-useless-escape
513
- eat(scnr, `\'`);
514
- let ch = '';
515
- let literal = '';
516
- while ((ch = takeChar(scnr, isLiteral))) {
517
- if (ch === '\\') {
518
- literal += readEscapeSequence(scnr);
519
- }
520
- else {
521
- literal += ch;
522
- }
523
- }
524
- const current = scnr.currentChar();
525
- if (current === CHAR_LF || current === EOF) {
526
- emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
527
- // TODO: Is it correct really?
528
- if (current === CHAR_LF) {
529
- scnr.next();
530
- // eslint-disable-next-line no-useless-escape
531
- eat(scnr, `\'`);
532
- }
533
- return literal;
534
- }
535
- // eslint-disable-next-line no-useless-escape
536
- eat(scnr, `\'`);
537
- return literal;
538
- }
539
- function readEscapeSequence(scnr) {
540
- const ch = scnr.currentChar();
541
- switch (ch) {
542
- case '\\':
543
- case `\'`: // eslint-disable-line no-useless-escape
544
- scnr.next();
545
- return `\\${ch}`;
546
- case 'u':
547
- return readUnicodeEscapeSequence(scnr, ch, 4);
548
- case 'U':
549
- return readUnicodeEscapeSequence(scnr, ch, 6);
550
- default:
551
- emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
552
- return '';
553
- }
554
- }
555
- function readUnicodeEscapeSequence(scnr, unicode, digits) {
556
- eat(scnr, unicode);
557
- let sequence = '';
558
- for (let i = 0; i < digits; i++) {
559
- const ch = takeHexDigit(scnr);
560
- if (!ch) {
561
- emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
562
- break;
563
- }
564
- sequence += ch;
565
- }
566
- return `\\${unicode}${sequence}`;
567
- }
568
- function isInvalidIdentifier(ch) {
569
- return (ch !== "{" /* TokenChars.BraceLeft */ &&
570
- ch !== "}" /* TokenChars.BraceRight */ &&
571
- ch !== CHAR_SP &&
572
- ch !== CHAR_LF);
573
- }
574
- function readInvalidIdentifier(scnr) {
575
- skipSpaces(scnr);
576
- let ch = '';
577
- let identifiers = '';
578
- while ((ch = takeChar(scnr, isInvalidIdentifier))) {
579
- identifiers += ch;
580
- }
581
- return identifiers;
582
- }
583
- function readLinkedModifier(scnr) {
584
- let ch = '';
585
- let name = '';
586
- while ((ch = takeIdentifierChar(scnr))) {
587
- name += ch;
588
- }
589
- return name;
590
- }
591
- function readLinkedRefer(scnr) {
592
- const fn = (buf) => {
593
- const ch = scnr.currentChar();
594
- if (ch === "{" /* TokenChars.BraceLeft */ ||
595
- ch === "@" /* TokenChars.LinkedAlias */ ||
596
- ch === "|" /* TokenChars.Pipe */ ||
597
- ch === "(" /* TokenChars.ParenLeft */ ||
598
- ch === ")" /* TokenChars.ParenRight */ ||
599
- !ch) {
600
- return buf;
601
- }
602
- else if (ch === CHAR_SP) {
603
- return buf;
604
- }
605
- else if (ch === CHAR_LF || ch === DOT) {
606
- buf += ch;
607
- scnr.next();
608
- return fn(buf);
609
- }
610
- else {
611
- buf += ch;
612
- scnr.next();
613
- return fn(buf);
614
- }
615
- };
616
- return fn('');
617
- }
618
- function readPlural(scnr) {
619
- skipSpaces(scnr);
620
- const plural = eat(scnr, "|" /* TokenChars.Pipe */);
621
- skipSpaces(scnr);
622
- return plural;
623
- }
624
- // TODO: We need refactoring of token parsing ...
625
- function readTokenInPlaceholder(scnr, context) {
626
- let token = null;
627
- const ch = scnr.currentChar();
628
- switch (ch) {
629
- case "{" /* TokenChars.BraceLeft */:
630
- if (context.braceNest >= 1) {
631
- emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
632
- }
633
- scnr.next();
634
- token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
635
- skipSpaces(scnr);
636
- context.braceNest++;
637
- return token;
638
- case "}" /* TokenChars.BraceRight */:
639
- if (context.braceNest > 0 &&
640
- context.currentType === 2 /* TokenTypes.BraceLeft */) {
641
- emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
642
- }
643
- scnr.next();
644
- token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
645
- context.braceNest--;
646
- context.braceNest > 0 && skipSpaces(scnr);
647
- if (context.inLinked && context.braceNest === 0) {
648
- context.inLinked = false;
649
- }
650
- return token;
651
- case "@" /* TokenChars.LinkedAlias */:
652
- if (context.braceNest > 0) {
653
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
654
- }
655
- token = readTokenInLinked(scnr, context) || getEndToken(context);
656
- context.braceNest = 0;
657
- return token;
658
- default: {
659
- let validNamedIdentifier = true;
660
- let validListIdentifier = true;
661
- let validLiteral = true;
662
- if (isPluralStart(scnr)) {
663
- if (context.braceNest > 0) {
664
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
665
- }
666
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
667
- // reset
668
- context.braceNest = 0;
669
- context.inLinked = false;
670
- return token;
671
- }
672
- if (context.braceNest > 0 &&
673
- (context.currentType === 4 /* TokenTypes.Named */ ||
674
- context.currentType === 5 /* TokenTypes.List */ ||
675
- context.currentType === 6 /* TokenTypes.Literal */)) {
676
- emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
677
- context.braceNest = 0;
678
- return readToken(scnr, context);
679
- }
680
- if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
681
- token = getToken(context, 4 /* TokenTypes.Named */, readNamedIdentifier(scnr));
682
- skipSpaces(scnr);
683
- return token;
684
- }
685
- if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
686
- token = getToken(context, 5 /* TokenTypes.List */, readListIdentifier(scnr));
687
- skipSpaces(scnr);
688
- return token;
689
- }
690
- if ((validLiteral = isLiteralStart(scnr, context))) {
691
- token = getToken(context, 6 /* TokenTypes.Literal */, readLiteral(scnr));
692
- skipSpaces(scnr);
693
- return token;
694
- }
695
- if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
696
- // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
697
- token = getToken(context, 12 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
698
- emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
699
- skipSpaces(scnr);
700
- return token;
701
- }
702
- break;
703
- }
704
- }
705
- return token;
706
- }
707
- // TODO: We need refactoring of token parsing ...
708
- function readTokenInLinked(scnr, context) {
709
- const { currentType } = context;
710
- let token = null;
711
- const ch = scnr.currentChar();
712
- if ((currentType === 7 /* TokenTypes.LinkedAlias */ ||
713
- currentType === 8 /* TokenTypes.LinkedDot */ ||
714
- currentType === 11 /* TokenTypes.LinkedModifier */ ||
715
- currentType === 9 /* TokenTypes.LinkedDelimiter */) &&
716
- (ch === CHAR_LF || ch === CHAR_SP)) {
717
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
718
- }
719
- switch (ch) {
720
- case "@" /* TokenChars.LinkedAlias */:
721
- scnr.next();
722
- token = getToken(context, 7 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
723
- context.inLinked = true;
724
- return token;
725
- case "." /* TokenChars.LinkedDot */:
726
- skipSpaces(scnr);
727
- scnr.next();
728
- return getToken(context, 8 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
729
- case ":" /* TokenChars.LinkedDelimiter */:
730
- skipSpaces(scnr);
731
- scnr.next();
732
- return getToken(context, 9 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
733
- default:
734
- if (isPluralStart(scnr)) {
735
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
736
- // reset
737
- context.braceNest = 0;
738
- context.inLinked = false;
739
- return token;
740
- }
741
- if (isLinkedDotStart(scnr, context) ||
742
- isLinkedDelimiterStart(scnr, context)) {
743
- skipSpaces(scnr);
744
- return readTokenInLinked(scnr, context);
745
- }
746
- if (isLinkedModifierStart(scnr, context)) {
747
- skipSpaces(scnr);
748
- return getToken(context, 11 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
749
- }
750
- if (isLinkedReferStart(scnr, context)) {
751
- skipSpaces(scnr);
752
- if (ch === "{" /* TokenChars.BraceLeft */) {
753
- // scan the placeholder
754
- return readTokenInPlaceholder(scnr, context) || token;
755
- }
756
- else {
757
- return getToken(context, 10 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
758
- }
759
- }
760
- if (currentType === 7 /* TokenTypes.LinkedAlias */) {
761
- emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
762
- }
763
- context.braceNest = 0;
764
- context.inLinked = false;
765
- return readToken(scnr, context);
766
- }
767
- }
768
- // TODO: We need refactoring of token parsing ...
769
- function readToken(scnr, context) {
770
- let token = { type: 13 /* TokenTypes.EOF */ };
771
- if (context.braceNest > 0) {
772
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
773
- }
774
- if (context.inLinked) {
775
- return readTokenInLinked(scnr, context) || getEndToken(context);
776
- }
777
- const ch = scnr.currentChar();
778
- switch (ch) {
779
- case "{" /* TokenChars.BraceLeft */:
780
- return readTokenInPlaceholder(scnr, context) || getEndToken(context);
781
- case "}" /* TokenChars.BraceRight */:
782
- emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
783
- scnr.next();
784
- return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
785
- case "@" /* TokenChars.LinkedAlias */:
786
- return readTokenInLinked(scnr, context) || getEndToken(context);
787
- default: {
788
- if (isPluralStart(scnr)) {
789
- token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
790
- // reset
791
- context.braceNest = 0;
792
- context.inLinked = false;
793
- return token;
794
- }
795
- if (isTextStart(scnr)) {
796
- return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
797
- }
798
- break;
799
- }
800
- }
801
- return token;
802
- }
803
- function nextToken() {
804
- const { currentType, offset, startLoc, endLoc } = _context;
805
- _context.lastType = currentType;
806
- _context.lastOffset = offset;
807
- _context.lastStartLoc = startLoc;
808
- _context.lastEndLoc = endLoc;
809
- _context.offset = currentOffset();
810
- _context.startLoc = currentPosition();
811
- if (_scnr.currentChar() === EOF) {
812
- return getToken(_context, 13 /* TokenTypes.EOF */);
813
- }
814
- return readToken(_scnr, _context);
815
- }
816
- return {
817
- nextToken,
818
- currentOffset,
819
- currentPosition,
820
- context
821
- };
822
- }
823
-
824
- const ERROR_DOMAIN = 'parser';
825
- // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
826
- const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
827
- function fromEscapeSequence(match, codePoint4, codePoint6) {
828
- switch (match) {
829
- case `\\\\`:
830
- return `\\`;
831
- // eslint-disable-next-line no-useless-escape
832
- case `\\\'`:
833
- // eslint-disable-next-line no-useless-escape
834
- return `\'`;
835
- default: {
836
- const codePoint = parseInt(codePoint4 || codePoint6, 16);
837
- if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
838
- return String.fromCodePoint(codePoint);
839
- }
840
- // invalid ...
841
- // Replace them with U+FFFD REPLACEMENT CHARACTER.
842
- return '�';
843
- }
844
- }
845
- }
846
- function createParser(options = {}) {
847
- const location = options.location !== false;
848
- const { onError } = options;
849
- function emitError(tokenzer, code, start, offset, ...args) {
850
- const end = tokenzer.currentPosition();
851
- end.offset += offset;
852
- end.column += offset;
853
- if (onError) {
854
- const loc = location ? createLocation(start, end) : null;
855
- const err = createCompileError(code, loc, {
856
- domain: ERROR_DOMAIN,
857
- args
858
- });
859
- onError(err);
860
- }
861
- }
862
- function startNode(type, offset, loc) {
863
- const node = { type };
864
- if (location) {
865
- node.start = offset;
866
- node.end = offset;
867
- node.loc = { start: loc, end: loc };
868
- }
869
- return node;
870
- }
871
- function endNode(node, offset, pos, type) {
872
- if (location) {
873
- node.end = offset;
874
- if (node.loc) {
875
- node.loc.end = pos;
876
- }
877
- }
878
- }
879
- function parseText(tokenizer, value) {
880
- const context = tokenizer.context();
881
- const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
882
- node.value = value;
883
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
884
- return node;
885
- }
886
- function parseList(tokenizer, index) {
887
- const context = tokenizer.context();
888
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
889
- const node = startNode(5 /* NodeTypes.List */, offset, loc);
890
- node.index = parseInt(index, 10);
891
- tokenizer.nextToken(); // skip brach right
892
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
893
- return node;
894
- }
895
- function parseNamed(tokenizer, key) {
896
- const context = tokenizer.context();
897
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
898
- const node = startNode(4 /* NodeTypes.Named */, offset, loc);
899
- node.key = key;
900
- tokenizer.nextToken(); // skip brach right
901
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
902
- return node;
903
- }
904
- function parseLiteral(tokenizer, value) {
905
- const context = tokenizer.context();
906
- const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
907
- const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
908
- node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
909
- tokenizer.nextToken(); // skip brach right
910
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
911
- return node;
912
- }
913
- function parseLinkedModifier(tokenizer) {
914
- const token = tokenizer.nextToken();
915
- const context = tokenizer.context();
916
- const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
917
- const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
918
- if (token.type !== 11 /* TokenTypes.LinkedModifier */) {
919
- // empty modifier
920
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
921
- node.value = '';
922
- endNode(node, offset, loc);
923
- return {
924
- nextConsumeToken: token,
925
- node
926
- };
927
- }
928
- // check token
929
- if (token.value == null) {
930
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
931
- }
932
- node.value = token.value || '';
933
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
934
- return {
935
- node
936
- };
937
- }
938
- function parseLinkedKey(tokenizer, value) {
939
- const context = tokenizer.context();
940
- const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
941
- node.value = value;
942
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
943
- return node;
944
- }
945
- function parseLinked(tokenizer) {
946
- const context = tokenizer.context();
947
- const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
948
- let token = tokenizer.nextToken();
949
- if (token.type === 8 /* TokenTypes.LinkedDot */) {
950
- const parsed = parseLinkedModifier(tokenizer);
951
- linkedNode.modifier = parsed.node;
952
- token = parsed.nextConsumeToken || tokenizer.nextToken();
953
- }
954
- // asset check token
955
- if (token.type !== 9 /* TokenTypes.LinkedDelimiter */) {
956
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
957
- }
958
- token = tokenizer.nextToken();
959
- // skip brace left
960
- if (token.type === 2 /* TokenTypes.BraceLeft */) {
961
- token = tokenizer.nextToken();
962
- }
963
- switch (token.type) {
964
- case 10 /* TokenTypes.LinkedKey */:
965
- if (token.value == null) {
966
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
967
- }
968
- linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
969
- break;
970
- case 4 /* TokenTypes.Named */:
971
- if (token.value == null) {
972
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
973
- }
974
- linkedNode.key = parseNamed(tokenizer, token.value || '');
975
- break;
976
- case 5 /* TokenTypes.List */:
977
- if (token.value == null) {
978
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
979
- }
980
- linkedNode.key = parseList(tokenizer, token.value || '');
981
- break;
982
- case 6 /* TokenTypes.Literal */:
983
- if (token.value == null) {
984
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
985
- }
986
- linkedNode.key = parseLiteral(tokenizer, token.value || '');
987
- break;
988
- default: {
989
- // empty key
990
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
991
- const nextContext = tokenizer.context();
992
- const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
993
- emptyLinkedKeyNode.value = '';
994
- endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
995
- linkedNode.key = emptyLinkedKeyNode;
996
- endNode(linkedNode, nextContext.offset, nextContext.startLoc);
997
- return {
998
- nextConsumeToken: token,
999
- node: linkedNode
1000
- };
1001
- }
1002
- }
1003
- endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
1004
- return {
1005
- node: linkedNode
1006
- };
1007
- }
1008
- function parseMessage(tokenizer) {
1009
- const context = tokenizer.context();
1010
- const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
1011
- ? tokenizer.currentOffset()
1012
- : context.offset;
1013
- const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
1014
- ? context.endLoc
1015
- : context.startLoc;
1016
- const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
1017
- node.items = [];
1018
- let nextToken = null;
1019
- do {
1020
- const token = nextToken || tokenizer.nextToken();
1021
- nextToken = null;
1022
- switch (token.type) {
1023
- case 0 /* TokenTypes.Text */:
1024
- if (token.value == null) {
1025
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1026
- }
1027
- node.items.push(parseText(tokenizer, token.value || ''));
1028
- break;
1029
- case 5 /* TokenTypes.List */:
1030
- if (token.value == null) {
1031
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1032
- }
1033
- node.items.push(parseList(tokenizer, token.value || ''));
1034
- break;
1035
- case 4 /* TokenTypes.Named */:
1036
- if (token.value == null) {
1037
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1038
- }
1039
- node.items.push(parseNamed(tokenizer, token.value || ''));
1040
- break;
1041
- case 6 /* TokenTypes.Literal */:
1042
- if (token.value == null) {
1043
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
1044
- }
1045
- node.items.push(parseLiteral(tokenizer, token.value || ''));
1046
- break;
1047
- case 7 /* TokenTypes.LinkedAlias */: {
1048
- const parsed = parseLinked(tokenizer);
1049
- node.items.push(parsed.node);
1050
- nextToken = parsed.nextConsumeToken || null;
1051
- break;
1052
- }
1053
- }
1054
- } while (context.currentType !== 13 /* TokenTypes.EOF */ &&
1055
- context.currentType !== 1 /* TokenTypes.Pipe */);
1056
- // adjust message node loc
1057
- const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
1058
- ? context.lastOffset
1059
- : tokenizer.currentOffset();
1060
- const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
1061
- ? context.lastEndLoc
1062
- : tokenizer.currentPosition();
1063
- endNode(node, endOffset, endLoc);
1064
- return node;
1065
- }
1066
- function parsePlural(tokenizer, offset, loc, msgNode) {
1067
- const context = tokenizer.context();
1068
- let hasEmptyMessage = msgNode.items.length === 0;
1069
- const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
1070
- node.cases = [];
1071
- node.cases.push(msgNode);
1072
- do {
1073
- const msg = parseMessage(tokenizer);
1074
- if (!hasEmptyMessage) {
1075
- hasEmptyMessage = msg.items.length === 0;
1076
- }
1077
- node.cases.push(msg);
1078
- } while (context.currentType !== 13 /* TokenTypes.EOF */);
1079
- if (hasEmptyMessage) {
1080
- emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
1081
- }
1082
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1083
- return node;
1084
- }
1085
- function parseResource(tokenizer) {
1086
- const context = tokenizer.context();
1087
- const { offset, startLoc } = context;
1088
- const msgNode = parseMessage(tokenizer);
1089
- if (context.currentType === 13 /* TokenTypes.EOF */) {
1090
- return msgNode;
1091
- }
1092
- else {
1093
- return parsePlural(tokenizer, offset, startLoc, msgNode);
1094
- }
1095
- }
1096
- function parse(source) {
1097
- const tokenizer = createTokenizer(source, shared.assign({}, options));
1098
- const context = tokenizer.context();
1099
- const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
1100
- if (location && node.loc) {
1101
- node.loc.source = source;
1102
- }
1103
- node.body = parseResource(tokenizer);
1104
- if (options.onCacheKey) {
1105
- node.cacheKey = options.onCacheKey(source);
1106
- }
1107
- // assert whether achieved to EOF
1108
- if (context.currentType !== 13 /* TokenTypes.EOF */) {
1109
- emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
1110
- }
1111
- endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
1112
- return node;
1113
- }
1114
- return { parse };
1115
- }
1116
- function getTokenCaption(token) {
1117
- if (token.type === 13 /* TokenTypes.EOF */) {
1118
- return 'EOF';
1119
- }
1120
- const name = (token.value || '').replace(/\r?\n/gu, '\\n');
1121
- return name.length > 10 ? name.slice(0, 9) + '…' : name;
1122
- }
1123
-
1124
- function createTransformer(ast, options = {} // eslint-disable-line
1125
- ) {
1126
- const _context = {
1127
- ast,
1128
- helpers: new Set()
1129
- };
1130
- const context = () => _context;
1131
- const helper = (name) => {
1132
- _context.helpers.add(name);
1133
- return name;
1134
- };
1135
- return { context, helper };
1136
- }
1137
- function traverseNodes(nodes, transformer) {
1138
- for (let i = 0; i < nodes.length; i++) {
1139
- traverseNode(nodes[i], transformer);
1140
- }
1141
- }
1142
- function traverseNode(node, transformer) {
1143
- // TODO: if we need pre-hook of transform, should be implemented to here
1144
- switch (node.type) {
1145
- case 1 /* NodeTypes.Plural */:
1146
- traverseNodes(node.cases, transformer);
1147
- transformer.helper("plural" /* HelperNameMap.PLURAL */);
1148
- break;
1149
- case 2 /* NodeTypes.Message */:
1150
- traverseNodes(node.items, transformer);
1151
- break;
1152
- case 6 /* NodeTypes.Linked */: {
1153
- const linked = node;
1154
- traverseNode(linked.key, transformer);
1155
- transformer.helper("linked" /* HelperNameMap.LINKED */);
1156
- transformer.helper("type" /* HelperNameMap.TYPE */);
1157
- break;
1158
- }
1159
- case 5 /* NodeTypes.List */:
1160
- transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1161
- transformer.helper("list" /* HelperNameMap.LIST */);
1162
- break;
1163
- case 4 /* NodeTypes.Named */:
1164
- transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
1165
- transformer.helper("named" /* HelperNameMap.NAMED */);
1166
- break;
1167
- }
1168
- // TODO: if we need post-hook of transform, should be implemented to here
1169
- }
1170
- // transform AST
1171
- function transform(ast, options = {} // eslint-disable-line
1172
- ) {
1173
- const transformer = createTransformer(ast);
1174
- transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
1175
- // traverse
1176
- ast.body && traverseNode(ast.body, transformer);
1177
- // set meta information
1178
- const context = transformer.context();
1179
- ast.helpers = Array.from(context.helpers);
1180
- }
1181
-
1182
- function optimize(ast) {
1183
- const body = ast.body;
1184
- if (body.type === 2 /* NodeTypes.Message */) {
1185
- optimizeMessageNode(body);
1186
- }
1187
- else {
1188
- body.cases.forEach(c => optimizeMessageNode(c));
1189
- }
1190
- return ast;
1191
- }
1192
- function optimizeMessageNode(message) {
1193
- if (message.items.length === 1) {
1194
- const item = message.items[0];
1195
- if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1196
- message.static = item.value;
1197
- delete item.value; // optimization for size
1198
- }
1199
- }
1200
- else {
1201
- const values = [];
1202
- for (let i = 0; i < message.items.length; i++) {
1203
- const item = message.items[i];
1204
- if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
1205
- break;
1206
- }
1207
- if (item.value == null) {
1208
- break;
1209
- }
1210
- values.push(item.value);
1211
- }
1212
- if (values.length === message.items.length) {
1213
- message.static = shared.join(values);
1214
- for (let i = 0; i < message.items.length; i++) {
1215
- const item = message.items[i];
1216
- if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
1217
- delete item.value; // optimization for size
1218
- }
1219
- }
1220
- }
1221
- }
1222
- }
1223
-
1224
- /* eslint-disable @typescript-eslint/no-explicit-any */
1225
- function minify(node) {
1226
- node.t = node.type;
1227
- switch (node.type) {
1228
- case 0 /* NodeTypes.Resource */: {
1229
- const resource = node;
1230
- minify(resource.body);
1231
- resource.b = resource.body;
1232
- delete resource.body;
1233
- break;
1234
- }
1235
- case 1 /* NodeTypes.Plural */: {
1236
- const plural = node;
1237
- const cases = plural.cases;
1238
- for (let i = 0; i < cases.length; i++) {
1239
- minify(cases[i]);
1240
- }
1241
- plural.c = cases;
1242
- delete plural.cases;
1243
- break;
1244
- }
1245
- case 2 /* NodeTypes.Message */: {
1246
- const message = node;
1247
- const items = message.items;
1248
- for (let i = 0; i < items.length; i++) {
1249
- minify(items[i]);
1250
- }
1251
- message.i = items;
1252
- delete message.items;
1253
- if (message.static) {
1254
- message.s = message.static;
1255
- delete message.static;
1256
- }
1257
- break;
1258
- }
1259
- case 3 /* NodeTypes.Text */:
1260
- case 9 /* NodeTypes.Literal */:
1261
- case 8 /* NodeTypes.LinkedModifier */:
1262
- case 7 /* NodeTypes.LinkedKey */: {
1263
- const valueNode = node;
1264
- if (valueNode.value) {
1265
- valueNode.v = valueNode.value;
1266
- delete valueNode.value;
1267
- }
1268
- break;
1269
- }
1270
- case 6 /* NodeTypes.Linked */: {
1271
- const linked = node;
1272
- minify(linked.key);
1273
- linked.k = linked.key;
1274
- delete linked.key;
1275
- if (linked.modifier) {
1276
- minify(linked.modifier);
1277
- linked.m = linked.modifier;
1278
- delete linked.modifier;
1279
- }
1280
- break;
1281
- }
1282
- case 5 /* NodeTypes.List */: {
1283
- const list = node;
1284
- list.i = list.index;
1285
- delete list.index;
1286
- break;
1287
- }
1288
- case 4 /* NodeTypes.Named */: {
1289
- const named = node;
1290
- named.k = named.key;
1291
- delete named.key;
1292
- break;
1293
- }
1294
- }
1295
- delete node.type;
1296
- }
1297
- /* eslint-enable @typescript-eslint/no-explicit-any */
1298
-
1299
- // eslint-disable-next-line @typescript-eslint/triple-slash-reference
1300
- /// <reference types="source-map-js" />
1301
- function createCodeGenerator(ast, options) {
1302
- const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
1303
- const location = options.location !== false;
1304
- const _context = {
1305
- filename,
1306
- code: '',
1307
- column: 1,
1308
- line: 1,
1309
- offset: 0,
1310
- map: undefined,
1311
- breakLineCode,
1312
- needIndent: _needIndent,
1313
- indentLevel: 0
1314
- };
1315
- if (location && ast.loc) {
1316
- _context.source = ast.loc.source;
1317
- }
1318
- const context = () => _context;
1319
- function push(code, node) {
1320
- _context.code += code;
1321
- if (_context.map) {
1322
- if (node && node.loc && node.loc !== LOCATION_STUB) {
1323
- addMapping(node.loc.start, getMappingName(node));
1324
- }
1325
- advancePositionWithSource(_context, code);
1326
- }
1327
- }
1328
- function _newline(n, withBreakLine = true) {
1329
- const _breakLineCode = withBreakLine ? breakLineCode : '';
1330
- push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
1331
- }
1332
- function indent(withNewLine = true) {
1333
- const level = ++_context.indentLevel;
1334
- withNewLine && _newline(level);
1335
- }
1336
- function deindent(withNewLine = true) {
1337
- const level = --_context.indentLevel;
1338
- withNewLine && _newline(level);
1339
- }
1340
- function newline() {
1341
- _newline(_context.indentLevel);
1342
- }
1343
- const helper = (key) => `_${key}`;
1344
- const needIndent = () => _context.needIndent;
1345
- function addMapping(loc, name) {
1346
- _context.map.addMapping({
1347
- name,
1348
- source: _context.filename,
1349
- original: {
1350
- line: loc.line,
1351
- column: loc.column - 1
1352
- },
1353
- generated: {
1354
- line: _context.line,
1355
- column: _context.column - 1
1356
- }
1357
- });
1358
- }
1359
- if (location && sourceMap) {
1360
- _context.map = new sourceMapJs.SourceMapGenerator();
1361
- _context.map.setSourceContent(filename, _context.source);
1362
- }
1363
- return {
1364
- context,
1365
- push,
1366
- indent,
1367
- deindent,
1368
- newline,
1369
- helper,
1370
- needIndent
1371
- };
1372
- }
1373
- function generateLinkedNode(generator, node) {
1374
- const { helper } = generator;
1375
- generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
1376
- generateNode(generator, node.key);
1377
- if (node.modifier) {
1378
- generator.push(`, `);
1379
- generateNode(generator, node.modifier);
1380
- generator.push(`, _type`);
1381
- }
1382
- else {
1383
- generator.push(`, undefined, _type`);
1384
- }
1385
- generator.push(`)`);
1386
- }
1387
- function generateMessageNode(generator, node) {
1388
- const { helper, needIndent } = generator;
1389
- generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
1390
- generator.indent(needIndent());
1391
- const length = node.items.length;
1392
- for (let i = 0; i < length; i++) {
1393
- generateNode(generator, node.items[i]);
1394
- if (i === length - 1) {
1395
- break;
1396
- }
1397
- generator.push(', ');
1398
- }
1399
- generator.deindent(needIndent());
1400
- generator.push('])');
1401
- }
1402
- function generatePluralNode(generator, node) {
1403
- const { helper, needIndent } = generator;
1404
- if (node.cases.length > 1) {
1405
- generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
1406
- generator.indent(needIndent());
1407
- const length = node.cases.length;
1408
- for (let i = 0; i < length; i++) {
1409
- generateNode(generator, node.cases[i]);
1410
- if (i === length - 1) {
1411
- break;
1412
- }
1413
- generator.push(', ');
1414
- }
1415
- generator.deindent(needIndent());
1416
- generator.push(`])`);
1417
- }
1418
- }
1419
- function generateResource(generator, node) {
1420
- if (node.body) {
1421
- generateNode(generator, node.body);
1422
- }
1423
- else {
1424
- generator.push('null');
1425
- }
1426
- }
1427
- function generateNode(generator, node) {
1428
- const { helper } = generator;
1429
- switch (node.type) {
1430
- case 0 /* NodeTypes.Resource */:
1431
- generateResource(generator, node);
1432
- break;
1433
- case 1 /* NodeTypes.Plural */:
1434
- generatePluralNode(generator, node);
1435
- break;
1436
- case 2 /* NodeTypes.Message */:
1437
- generateMessageNode(generator, node);
1438
- break;
1439
- case 6 /* NodeTypes.Linked */:
1440
- generateLinkedNode(generator, node);
1441
- break;
1442
- case 8 /* NodeTypes.LinkedModifier */:
1443
- generator.push(JSON.stringify(node.value), node);
1444
- break;
1445
- case 7 /* NodeTypes.LinkedKey */:
1446
- generator.push(JSON.stringify(node.value), node);
1447
- break;
1448
- case 5 /* NodeTypes.List */:
1449
- generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
1450
- break;
1451
- case 4 /* NodeTypes.Named */:
1452
- generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
1453
- break;
1454
- case 9 /* NodeTypes.Literal */:
1455
- generator.push(JSON.stringify(node.value), node);
1456
- break;
1457
- case 3 /* NodeTypes.Text */:
1458
- generator.push(JSON.stringify(node.value), node);
1459
- break;
1460
- }
1461
- }
1462
- // generate code from AST
1463
- const generate = (ast, options = {}) => {
1464
- const mode = shared.isString(options.mode) ? options.mode : 'normal';
1465
- const filename = shared.isString(options.filename)
1466
- ? options.filename
1467
- : 'message.intl';
1468
- const sourceMap = !!options.sourceMap;
1469
- // prettier-ignore
1470
- const breakLineCode = options.breakLineCode != null
1471
- ? options.breakLineCode
1472
- : mode === 'arrow'
1473
- ? ';'
1474
- : '\n';
1475
- const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
1476
- const helpers = ast.helpers || [];
1477
- const generator = createCodeGenerator(ast, {
1478
- mode,
1479
- filename,
1480
- sourceMap,
1481
- breakLineCode,
1482
- needIndent
1483
- });
1484
- generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
1485
- generator.indent(needIndent);
1486
- if (helpers.length > 0) {
1487
- generator.push(`const { ${shared.join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
1488
- generator.newline();
1489
- }
1490
- generator.push(`return `);
1491
- generateNode(generator, ast);
1492
- generator.deindent(needIndent);
1493
- generator.push(`}`);
1494
- delete ast.helpers;
1495
- const { code, map } = generator.context();
1496
- return {
1497
- ast,
1498
- code,
1499
- map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
1500
- };
1501
- };
1502
- function getMappingName(node) {
1503
- switch (node.type) {
1504
- case 3 /* NodeTypes.Text */:
1505
- case 9 /* NodeTypes.Literal */:
1506
- case 8 /* NodeTypes.LinkedModifier */:
1507
- case 7 /* NodeTypes.LinkedKey */:
1508
- return node.value;
1509
- case 5 /* NodeTypes.List */:
1510
- return node.index.toString();
1511
- case 4 /* NodeTypes.Named */:
1512
- return node.key;
1513
- default:
1514
- return undefined;
1515
- }
1516
- }
1517
- function advancePositionWithSource(pos, source, numberOfCharacters = source.length) {
1518
- let linesCount = 0;
1519
- let lastNewLinePos = -1;
1520
- for (let i = 0; i < numberOfCharacters; i++) {
1521
- if (source.charCodeAt(i) === 10 /* newline char code */) {
1522
- linesCount++;
1523
- lastNewLinePos = i;
1524
- }
1525
- }
1526
- pos.offset += numberOfCharacters;
1527
- pos.line += linesCount;
1528
- pos.column =
1529
- lastNewLinePos === -1
1530
- ? pos.column + numberOfCharacters
1531
- : numberOfCharacters - lastNewLinePos;
1532
- return pos;
1533
- }
1534
-
1535
- function baseCompile(source, options = {}) {
1536
- const assignedOptions = shared.assign({}, options);
1537
- const jit = !!assignedOptions.jit;
1538
- const enalbeMinify = !!assignedOptions.minify;
1539
- const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
1540
- // parse source codes
1541
- const parser = createParser(assignedOptions);
1542
- const ast = parser.parse(source);
1543
- if (!jit) {
1544
- // transform ASTs
1545
- transform(ast, assignedOptions);
1546
- // generate javascript codes
1547
- return generate(ast, assignedOptions);
1548
- }
1549
- else {
1550
- // optimize ASTs
1551
- enambeOptimize && optimize(ast);
1552
- // minimize ASTs
1553
- enalbeMinify && minify(ast);
1554
- // In JIT mode, no ast transform, no code generation.
1555
- return { ast, code: '' };
1556
- }
1557
- }
1558
-
1559
- exports.COMPILE_ERROR_CODES_EXTEND_POINT = COMPILE_ERROR_CODES_EXTEND_POINT;
1560
- exports.CompileErrorCodes = CompileErrorCodes;
1561
- exports.ERROR_DOMAIN = ERROR_DOMAIN;
1562
- exports.LOCATION_STUB = LOCATION_STUB;
1563
- exports.baseCompile = baseCompile;
1564
- exports.createCompileError = createCompileError;
1565
- exports.createLocation = createLocation;
1566
- exports.createParser = createParser;
1567
- exports.createPosition = createPosition;
1568
- exports.defaultOnError = defaultOnError;
1569
- exports.detectHtmlTag = detectHtmlTag;
1570
- exports.errorMessages = errorMessages;