Debian Codegraph @

node/gettext-parser/lib/poparser.js

raw
1 import encoding from 'encoding';
2 import { formatCharset, parseNPluralFromHeadersSafely, parseHeader } from './shared.js';
3 import { Transform } from 'node:stream';
4 import util from 'node:util';
5
6 /**
7 * Parses a PO object into translation table
8 *
9 * @typedef {{ defaultCharset?: string, validation?: boolean }} Options
10 * @param {string | Buffer} input PO object
11 * @param {Options} [options] Optional options with defaultCharset and validation
12 */
13 export function parse (input, options = {}) {
14 const parser = new Parser(input, options);
15
16 return parser.parse();
17 };
18
19 /**
20 * Parses a PO stream, emits translation table in object mode
21 *
22 * @typedef {{ defaultCharset: strubg, validation: boolean }} Options
23 * @param {Options} [options] Optional options with defaultCharset and validation
24 * @param {import('node:stream').TransformOptions} [transformOptions] Optional stream options
25 */
26 export function stream (options = {}, transformOptions = {}) {
27 return new PoParserTransform(options, transformOptions);
28 };
29
30 /**
31 * Creates a PO parser object. If PO object is a string,
32 * UTF-8 will be used as the charset
33 *
34 * @typedef {{ defaultCharset?: string, validation?: boolean }} Options
35 * @constructor
36 * @param {string | Buffer} fileContents PO object
37 * @param {Options} options Options with defaultCharset and validation
38 */
39 function Parser (fileContents, { defaultCharset = 'iso-8859-1', validation = false }) {
40 this._validation = validation;
41 this._charset = defaultCharset;
42
43 this._lex = [];
44 this._escaped = false;
45 this._node = {};
46 this._state = this.states.none;
47 this._lineNumber = 1;
48
49 if (typeof fileContents === 'string') {
50 this._charset = 'utf-8';
51 this._fileContents = fileContents;
52 } else {
53 this._fileContents = this._handleCharset(fileContents);
54 }
55 }
56
57 /**
58 * Parses the PO object and returns translation table
59 *
60 * @return {Object} Translation table
61 */
62 Parser.prototype.parse = function () {
63 this._lexer(this._fileContents);
64
65 return this._finalize(this._lex);
66 };
67
68 /**
69 * Detects charset for PO strings from the header
70 *
71 * @param {Buffer} headers Header value
72 */
73 Parser.prototype._handleCharset = function (buf = '') {
74 const str = buf.toString();
75 let pos;
76 let headers = '';
77 let match;
78
79 if ((pos = str.search(/^\s*msgid/im)) >= 0) {
80 pos = pos + str.substr(pos + 5).search(/^\s*(msgid|msgctxt)/im);
81 headers = str.substr(0, pos >= 0 ? pos + 5 : str.length);
82 }
83
84 if ((match = headers.match(/[; ]charset\s*=\s*([\w-]+)(?:[\s;]|\\n)*"\s*$/mi))) {
85 this._charset = formatCharset(match[1], this._charset);
86 }
87
88 if (this._charset === 'utf-8') {
89 return str;
90 }
91
92 return this._toString(buf);
93 };
94
95 Parser.prototype._toString = function (buf) {
96 return encoding.convert(buf, 'utf-8', this._charset).toString('utf-8');
97 };
98
99 /**
100 * State constants for parsing FSM
101 */
102 Parser.prototype.states = {
103 none: 0x01,
104 comments: 0x02,
105 key: 0x03,
106 string: 0x04,
107 obsolete: 0x05
108 };
109
110 /**
111 * Value types for lexer
112 */
113 Parser.prototype.types = {
114 comments: 0x01,
115 key: 0x02,
116 string: 0x03,
117 obsolete: 0x04
118 };
119
120 /**
121 * String matches for lexer
122 */
123 Parser.prototype.symbols = {
124 quotes: /["']/,
125 comments: /#/,
126 whitespace: /\s/,
127 key: /[\w\-[\]]/,
128 keyNames: /^(?:msgctxt|msgid(?:_plural)?|msgstr(?:\[\d+])?)$/
129 };
130
131 /**
132 * Token parser. Parsed state can be found from this._lex
133 *
134 * @param {String} chunk String
135 */
136 Parser.prototype._lexer = function (chunk) {
137 let chr;
138
139 for (let i = 0, len = chunk.length; i < len; i++) {
140 chr = chunk.charAt(i);
141
142 if (chr === '\n') {
143 this._lineNumber += 1;
144 }
145
146 switch (this._state) {
147 case this.states.none:
148 case this.states.obsolete:
149 if (chr.match(this.symbols.quotes)) {
150 this._node = {
151 type: this.types.string,
152 value: '',
153 quote: chr
154 };
155 this._lex.push(this._node);
156 this._state = this.states.string;
157 } else if (chr.match(this.symbols.comments)) {
158 this._node = {
159 type: this.types.comments,
160 value: ''
161 };
162 this._lex.push(this._node);
163 this._state = this.states.comments;
164 } else if (chr === '|' && this._state === this.states.obsolete) {
165 // "#~|": previous string of an obsolete entry
166 this._node = {
167 type: this.types.comments,
168 value: chr
169 };
170 this._lex.push(this._node);
171 this._state = this.states.comments;
172 } else if (!chr.match(this.symbols.whitespace)) {
173 this._node = {
174 type: this.types.key,
175 value: chr
176 };
177 if (this._state === this.states.obsolete) {
178 this._node.obsolete = true;
179 }
180 this._lex.push(this._node);
181 this._state = this.states.key;
182 }
183 break;
184 case this.states.comments:
185 if (chr === '\n') {
186 this._state = this.states.none;
187 } else if (chr === '~' && this._node.value === '') {
188 this._node.value += chr;
189 this._state = this.states.obsolete;
190 } else if (chr !== '\r') {
191 this._node.value += chr;
192 }
193 break;
194 case this.states.string:
195 if (this._escaped) {
196 switch (chr) {
197 case 't':
198 this._node.value += '\t';
199 break;
200 case 'n':
201 this._node.value += '\n';
202 break;
203 case 'r':
204 this._node.value += '\r';
205 break;
206 default:
207 this._node.value += chr;
208 }
209 this._escaped = false;
210 } else {
211 if (chr === this._node.quote) {
212 this._state = this.states.none;
213 } else if (chr === '\\') {
214 this._escaped = true;
215 break;
216 } else {
217 this._node.value += chr;
218 }
219 this._escaped = false;
220 }
221 break;
222 case this.states.key:
223 if (!chr.match(this.symbols.key)) {
224 if (!this._node.value.match(this.symbols.keyNames)) {
225 const err = new SyntaxError(`Error parsing PO data: Invalid key name "${this._node.value}" at line ${this._lineNumber}. This can be caused by an unescaped quote character in a msgid or msgstr value.`);
226
227 err.lineNumber = this._lineNumber;
228
229 throw err;
230 }
231 this._state = this.states.none;
232 i--;
233 } else {
234 this._node.value += chr;
235 }
236 break;
237 }
238 }
239 };
240
241 /**
242 * Join multi line strings
243 *
244 * @param {Object} tokens Parsed tokens
245 * @return {Object} Parsed tokens, with multi line strings joined into one
246 */
247 Parser.prototype._joinStringValues = function (tokens) {
248 const response = [];
249 let lastNode;
250
251 for (let i = 0, len = tokens.length; i < len; i++) {
252 if (lastNode && tokens[i].type === this.types.string && lastNode.type === this.types.string) {
253 lastNode.value += tokens[i].value;
254 } else if (lastNode && tokens[i].type === this.types.comments && lastNode.type === this.types.comments) {
255 lastNode.value += '\n' + tokens[i].value;
256 } else {
257 response.push(tokens[i]);
258 lastNode = tokens[i];
259 }
260 }
261
262 return response;
263 };
264
265 /**
266 * Parse comments into separate comment blocks
267 *
268 * @param {Object} tokens Parsed tokens
269 */
270 Parser.prototype._parseComments = function (tokens) {
271 // parse comments
272 tokens.forEach(node => {
273 if (!node || node.type !== this.types.comments) {
274 return;
275 }
276
277 const comment = {
278 translator: [],
279 extracted: [],
280 reference: [],
281 flag: [],
282 previous: []
283 };
284
285 const lines = (node.value || '').split(/\n/);
286
287 lines.forEach(line => {
288 switch (line.charAt(0) || '') {
289 case ':':
290 comment.reference.push(line.substr(1).trim());
291 break;
292 case '.':
293 comment.extracted.push(line.substr(1).replace(/^\s+/, ''));
294 break;
295 case ',':
296 comment.flag.push(line.substr(1).replace(/^\s+/, ''));
297 break;
298 case '|':
299 comment.previous.push(line.substr(1).replace(/^\s+/, ''));
300 break;
301 case '~':
302 break;
303 default:
304 comment.translator.push(line.replace(/^\s+/, ''));
305 }
306 });
307
308 node.value = {};
309
310 Object.keys(comment).forEach(key => {
311 if (comment[key] && comment[key].length) {
312 node.value[key] = comment[key].join('\n');
313 }
314 });
315 });
316 };
317
318 /**
319 * Join gettext keys with values
320 *
321 * @param {Object} tokens Parsed tokens
322 * @return {Object} Tokens
323 */
324 Parser.prototype._handleKeys = function (tokens) {
325 const response = [];
326 let lastNode;
327
328 for (let i = 0, len = tokens.length; i < len; i++) {
329 if (tokens[i].type === this.types.key) {
330 lastNode = {
331 key: tokens[i].value
332 };
333 if (tokens[i].obsolete) {
334 lastNode.obsolete = true;
335 }
336 if (i && tokens[i - 1].type === this.types.comments) {
337 lastNode.comments = tokens[i - 1].value;
338 }
339 lastNode.value = '';
340 response.push(lastNode);
341 } else if (tokens[i].type === this.types.string && lastNode) {
342 lastNode.value += tokens[i].value;
343 }
344 }
345
346 return response;
347 };
348
349 /**
350 * Separate different values into individual translation objects
351 *
352 * @param {Object} tokens Parsed tokens
353 * @return {Object} Tokens
354 */
355 Parser.prototype._handleValues = function (tokens) {
356 const response = [];
357 let lastNode;
358 let curContext;
359 let curComments;
360
361 for (let i = 0, len = tokens.length; i < len; i++) {
362 if (tokens[i].key.toLowerCase() === 'msgctxt') {
363 curContext = tokens[i].value;
364 curComments = tokens[i].comments;
365 } else if (tokens[i].key.toLowerCase() === 'msgid') {
366 lastNode = {
367 msgid: tokens[i].value
368 };
369 if (tokens[i].obsolete) {
370 lastNode.obsolete = true;
371 }
372
373 if (curContext) {
374 lastNode.msgctxt = curContext;
375 }
376
377 if (curComments) {
378 lastNode.comments = curComments;
379 }
380
381 if (tokens[i].comments && !lastNode.comments) {
382 lastNode.comments = tokens[i].comments;
383 }
384
385 curContext = false;
386 curComments = false;
387 response.push(lastNode);
388 } else if (tokens[i].key.toLowerCase() === 'msgid_plural') {
389 if (lastNode) {
390 if (this._validation && 'msgid_plural' in lastNode) {
391 throw new SyntaxError(`Multiple msgid_plural error: entry "${lastNode.msgid}" in "${lastNode.msgctxt || ''}" context has multiple msgid_plural declarations.`);
392 }
393
394 lastNode.msgid_plural = tokens[i].value;
395 }
396
397 if (tokens[i].comments && !lastNode.comments) {
398 lastNode.comments = tokens[i].comments;
399 }
400
401 curContext = false;
402 curComments = false;
403 } else if (tokens[i].key.substr(0, 6).toLowerCase() === 'msgstr') {
404 if (lastNode) {
405 lastNode.msgstr = (lastNode.msgstr || []).concat(tokens[i].value);
406 }
407
408 if (tokens[i].comments && !lastNode.comments) {
409 lastNode.comments = tokens[i].comments;
410 }
411
412 curContext = false;
413 curComments = false;
414 }
415 }
416
417 return response;
418 };
419
420 /**
421 * Validate token
422 *
423 * @param {Object} token Parsed token
424 * @param {Object} translations Translation table
425 * @param {string} msgctxt Message entry context
426 * @param {number} nplurals Number of epected plural forms
427 * @throws Will throw an error if token validation fails
428 */
429 Parser.prototype._validateToken = function (
430 {
431 msgid = '',
432 msgid_plural = '',
433 msgstr = []
434 },
435 translations,
436 msgctxt,
437 nplurals
438 ) {
439 if (!this._validation) {
440 return;
441 }
442
443 if (msgid in translations[msgctxt]) {
444 throw new SyntaxError(`Duplicate msgid error: entry "${msgid}" in "${msgctxt}" context has already been declared.`);
445 } else if (msgid_plural && msgstr.length !== nplurals) {
446 throw new RangeError(`Plural forms range error: Expected to find ${nplurals} forms but got ${msgstr.length} for entry "${msgid_plural}" in "${msgctxt}" context.`);
447 } else if (!msgid_plural && msgstr.length !== 1) {
448 throw new RangeError(`Translation string range error: Extected 1 msgstr definitions associated with "${msgid}" in "${msgctxt}" context, found ${msgstr.length}.`);
449 }
450 };
451
452 /**
453 * Compose a translation table from tokens object
454 *
455 * @param {Object} tokens Parsed tokens
456 * @return {Object} Translation table
457 */
458 Parser.prototype._normalize = function (tokens) {
459 const table = {
460 charset: this._charset,
461 headers: undefined,
462 translations: {}
463 };
464 let nplurals = 1;
465 let msgctxt;
466
467 for (let i = 0, len = tokens.length; i < len; i++) {
468 msgctxt = tokens[i].msgctxt || '';
469
470 if (tokens[i].obsolete) {
471 if (!table.obsolete) {
472 table.obsolete = {};
473 }
474
475 if (!Object.hasOwn(table.obsolete, msgctxt)) {
476 Object.defineProperty(table.obsolete, msgctxt, { value: {}, writable: true, enumerable: true, configurable: true });
477 }
478
479 delete tokens[i].obsolete;
480
481 Object.defineProperty(table.obsolete[msgctxt], tokens[i].msgid, { value: tokens[i], writable: true, enumerable: true, configurable: true });
482
483 continue;
484 }
485
486 if (!Object.hasOwn(table.translations, msgctxt)) {
487 Object.defineProperty(table.translations, msgctxt, { value: {}, writable: true, enumerable: true, configurable: true });
488 }
489
490 if (!table.headers && !msgctxt && !tokens[i].msgid) {
491 table.headers = parseHeader(tokens[i].msgstr[0]);
492 nplurals = parseNPluralFromHeadersSafely(table.headers, nplurals);
493 }
494
495 this._validateToken(tokens[i], table.translations, msgctxt, nplurals);
496
497 Object.defineProperty(table.translations[msgctxt], tokens[i].msgid, { value: tokens[i], writable: true, enumerable: true, configurable: true });
498 }
499
500 return table;
501 };
502
503 /**
504 * Converts parsed tokens to a translation table
505 *
506 * @param {Object} tokens Parsed tokens
507 * @returns {Object} Translation table
508 */
509 Parser.prototype._finalize = function (tokens) {
510 let data = this._joinStringValues(tokens);
511
512 this._parseComments(data);
513
514 data = this._handleKeys(data);
515 data = this._handleValues(data);
516
517 return this._normalize(data);
518 };
519
520 /**
521 * Creates a transform stream for parsing PO input
522 *
523 * @typedef {{ defaultCharset: strubg, validation: boolean }} Options
524 * @constructor
525 * @param {Options} options Optional options with defaultCharset and validation
526 * @param {import('node:stream').TransformOptions} transformOptions Optional stream options
527 */
528 function PoParserTransform (options, transformOptions) {
529 this.options = options;
530 this._parser = false;
531 this._tokens = {};
532
533 this._cache = [];
534 this._cacheSize = 0;
535
536 this.initialTreshold = transformOptions.initialTreshold || 2 * 1024;
537
538 Transform.call(this, transformOptions);
539 this._writableState.objectMode = false;
540 this._readableState.objectMode = true;
541 }
542 util.inherits(PoParserTransform, Transform);
543
544 /**
545 * Processes a chunk of the input stream
546 */
547 PoParserTransform.prototype._transform = function (chunk, encoding, done) {
548 let i;
549 let len = 0;
550
551 if (!chunk || !chunk.length) {
552 return done();
553 }
554
555 if (!this._parser) {
556 this._cache.push(chunk);
557 this._cacheSize += chunk.length;
558
559 // wait until the first 1kb before parsing headers for charset
560 if (this._cacheSize < this.initialTreshold) {
561 return setImmediate(done);
562 } else if (this._cacheSize) {
563 chunk = Buffer.concat(this._cache, this._cacheSize);
564 this._cacheSize = 0;
565 this._cache = [];
566 }
567
568 this._parser = new Parser(chunk, this.options);
569 } else if (this._cacheSize) {
570 // this only happens if we had an uncompleted 8bit sequence from the last iteration
571 this._cache.push(chunk);
572 this._cacheSize += chunk.length;
573 chunk = Buffer.concat(this._cache, this._cacheSize);
574 this._cacheSize = 0;
575 this._cache = [];
576 }
577
578 // cache 8bit bytes from the end of the chunk
579 // helps if the chunk ends in the middle of an utf-8 sequence
580 for (i = chunk.length - 1; i >= 0; i--) {
581 if (chunk[i] >= 0x80) {
582 len++;
583 continue;
584 }
585 break;
586 }
587 // it seems we found some 8bit bytes from the end of the string, so let's cache these
588 if (len) {
589 this._cache = [chunk.slice(chunk.length - len)];
590 this._cacheSize = this._cache[0].length;
591 chunk = chunk.slice(0, chunk.length - len);
592 }
593
594 // chunk might be empty if it only continued of 8bit bytes and these were all cached
595 if (chunk.length) {
596 try {
597 this._parser._lexer(this._parser._toString(chunk));
598 } catch (error) {
599 setImmediate(() => {
600 done(error);
601 });
602
603 return;
604 }
605 }
606
607 setImmediate(done);
608 };
609
610 /**
611 * Once all input has been processed emit the parsed translation table as an object
612 */
613 PoParserTransform.prototype._flush = function (done) {
614 let chunk;
615
616 if (this._cacheSize) {
617 chunk = Buffer.concat(this._cache, this._cacheSize);
618 }
619
620 if (!this._parser && chunk) {
621 this._parser = new Parser(chunk, this.options);
622 }
623
624 if (chunk) {
625 try {
626 this._parser._lexer(this._parser._toString(chunk));
627 } catch (error) {
628 setImmediate(() => {
629 done(error);
630 });
631
632 return;
633 }
634 }
635
636 if (this._parser) {
637 this.push(this._parser._finalize(this._parser._lex));
638 }
639
640 setImmediate(done);
641 };