@intlify/message-compiler 9.3.0-beta.0 → 9.3.0-beta.10

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