Debian Codegraph @

node/gettext-parser/lib/pocompiler.js

raw
1 import { Buffer } from 'node:buffer';
2 import encoding from 'encoding';
3 import { HEADERS, foldLine, compareMsgid, formatCharset, generateHeader } from './shared.js';
4 import contentType from 'content-type';
5
6 /**
7 * Exposes general compiler function. Takes a translation
8 * object as a parameter and returns PO object
9 *
10 * @param {Object} table Translation object
11 * @return {Buffer} Compiled PO object
12 */
13 export default function (table, options) {
14 const compiler = new Compiler(table, options);
15
16 return compiler.compile();
17 };
18
19 /**
20 * Creates a PO compiler object.
21 *
22 * @constructor
23 * @param {Object} table Translation table to be compiled
24 */
25 function Compiler (table = {}, options = {}) {
26 this._table = table;
27 this._options = options;
28
29 this._table.translations = this._table.translations || {};
30
31 let { headers = {} } = this._table;
32
33 headers = Object.keys(headers).reduce((result, key) => {
34 const lowerKey = key.toLowerCase();
35
36 if (HEADERS.has(lowerKey)) {
37 result[HEADERS.get(lowerKey)] = headers[key];
38 } else {
39 result[key] = headers[key];
40 }
41
42 return result;
43 }, {});
44
45 this._table.headers = headers;
46
47 if (!('foldLength' in this._options)) {
48 this._options.foldLength = 76;
49 }
50
51 if (!('escapeCharacters' in this._options)) {
52 this._options.escapeCharacters = true;
53 }
54
55 if (!('sort' in this._options)) {
56 this._options.sort = false;
57 }
58
59 if (!('eol' in this._options)) {
60 this._options.eol = '\n';
61 }
62
63 this._translations = [];
64
65 this._handleCharset();
66 }
67
68 /**
69 * Converts a comments object to a comment string. The comment object is
70 * in the form of {translator:'', reference: '', extracted: '', flag: '', previous:''}
71 *
72 * @param {Object} comments A comments object
73 * @param {boolean} [obsolete] This comments object is for an obsolete block
74 * @return {String} A comment string for the PO file
75 */
76 Compiler.prototype._drawComments = function (comments, obsolete = false) {
77 const lines = [];
78 const types = [{
79 key: 'translator',
80 prefix: '# '
81 }, {
82 key: 'reference',
83 prefix: '#: '
84 }, {
85 key: 'extracted',
86 prefix: '#. '
87 }, {
88 key: 'flag',
89 prefix: '#, '
90 }, {
91 key: 'previous',
92 prefix: obsolete ? '#~| ' : '#| '
93 }];
94
95 types.forEach(type => {
96 if (!comments[type.key]) {
97 return;
98 }
99
100 comments[type.key].split(/\r?\n|\r/).forEach(line => {
101 lines.push(`${type.prefix}${line}`);
102 });
103 });
104
105 return lines.join(this._options.eol);
106 };
107
108 /**
109 * Builds a PO string for a single translation object
110 *
111 * @param {Object} block Translation object
112 * @param {Object} [override] Properties of this object will override `block` properties
113 * @param {boolean} [obsolete] Block is obsolete and must be commented out
114 * @return {String} Translation string for a single object
115 */
116 Compiler.prototype._drawBlock = function (block, override = {}, obsolete = false) {
117 const response = [];
118 const msgctxt = override.msgctxt || block.msgctxt;
119 const msgid = override.msgid || block.msgid;
120 const msgidPlural = override.msgid_plural || block.msgid_plural;
121 const msgstr = [].concat(override.msgstr || block.msgstr);
122 let comments = override.comments || block.comments;
123
124 // add comments
125 if (comments && (comments = this._drawComments(comments, obsolete))) {
126 response.push(comments);
127 }
128
129 if (msgctxt) {
130 response.push(this._addPOString('msgctxt', msgctxt, obsolete));
131 }
132
133 response.push(this._addPOString('msgid', msgid || '', obsolete));
134
135 if (msgidPlural) {
136 response.push(this._addPOString('msgid_plural', msgidPlural, obsolete));
137
138 msgstr.forEach((msgstr, i) => {
139 response.push(this._addPOString(`msgstr[${i}]`, msgstr || '', obsolete));
140 });
141 } else {
142 response.push(this._addPOString('msgstr', msgstr[0] || '', obsolete));
143 }
144
145 return response.join(this._options.eol);
146 };
147
148 /**
149 * Escapes and joins a key and a value for the PO string
150 *
151 * @param {String} key Key name
152 * @param {String} value Key value
153 * @param {boolean} [obsolete] PO string is obsolete and must be commented out
154 * @return {String} Joined and escaped key-value pair
155 */
156 Compiler.prototype._addPOString = function (key = '', value = '', obsolete = false) {
157 key = key.toString();
158 if (obsolete) {
159 key = '#~ ' + key;
160 }
161
162 let { foldLength, eol, escapeCharacters } = this._options;
163
164 // escape newlines and quotes
165 if (escapeCharacters) {
166 value = value.toString()
167 .replace(/\\/g, '\\\\')
168 .replace(/"/g, '\\"')
169 .replace(/\t/g, '\\t')
170 .replace(/\r/g, '\\r');
171 }
172
173 value = value.replace(/\n/g, '\\n'); // need to escape new line characters regardless
174
175 let lines = [value];
176
177 if (obsolete) {
178 eol = eol + '#~ ';
179 }
180
181 if (foldLength > 0) {
182 lines = foldLine(value, foldLength);
183 } else {
184 // split only on new lines
185 if (escapeCharacters) {
186 lines = value.split(/\\n/g);
187 for (let i = 0; i < lines.length - 1; i++) {
188 lines[i] = `${lines[i]}\\n`;
189 }
190 if (lines.length && lines[lines.length - 1] === '') {
191 lines.splice(-1, 1);
192 }
193 }
194 }
195
196 if (lines.length < 2) {
197 return `${key} "${lines.shift() || ''}"`;
198 }
199
200 return `${key} ""${eol}"${lines.join(`"${eol}"`)}"`;
201 };
202
203 /**
204 * Handles header values, replaces or adds (if needed) a charset property
205 */
206 Compiler.prototype._handleCharset = function () {
207 const ct = contentType.parse(this._table.headers['Content-Type'] || 'text/plain');
208
209 const charset = formatCharset(this._table.charset || ct.parameters.charset || 'utf-8');
210
211 // clean up content-type charset independently using fallback if missing
212 if (ct.parameters.charset) {
213 ct.parameters.charset = formatCharset(ct.parameters.charset);
214 }
215
216 this._table.charset = charset;
217 this._table.headers['Content-Type'] = contentType.format(ct);
218 };
219
220 /**
221 * Flatten and sort translations object
222 *
223 * @param {Object} section Object to be prepared (translations or obsolete)
224 * @returns {Array} Prepared array
225 */
226 Compiler.prototype._prepareSection = function (section) {
227 let response = [];
228
229 Object.keys(section).forEach(msgctxt => {
230 if (typeof section[msgctxt] !== 'object') {
231 return;
232 }
233
234 Object.keys(section[msgctxt]).forEach(msgid => {
235 if (typeof section[msgctxt][msgid] !== 'object') {
236 return;
237 }
238
239 if (msgctxt === '' && msgid === '') {
240 return;
241 }
242
243 response.push(section[msgctxt][msgid]);
244 });
245 });
246
247 const { sort } = this._options;
248
249 if (sort !== false) {
250 if (typeof sort === 'function') {
251 response = response.sort(sort);
252 } else {
253 response = response.sort(compareMsgid);
254 }
255 }
256
257 return response;
258 };
259
260 /**
261 * Compiles translation object into a PO object
262 *
263 * @return {Buffer} Compiled PO object
264 */
265 Compiler.prototype.compile = function () {
266 const headerBlock = (this._table.translations[''] && this._table.translations['']['']) || {};
267 let response = [];
268
269 const translations = this._prepareSection(this._table.translations);
270 response = translations.map(r => this._drawBlock(r));
271
272 if (typeof this._table.obsolete === 'object') {
273 const obsolete = this._prepareSection(this._table.obsolete);
274 if (obsolete.length) {
275 response = response.concat(obsolete.map(r => this._drawBlock(r, {}, true)));
276 }
277 }
278
279 const { eol } = this._options;
280
281 response.unshift(this._drawBlock(headerBlock, {
282 msgstr: generateHeader(this._table.headers)
283 }));
284
285 if (this._table.charset === 'utf-8' || this._table.charset === 'ascii') {
286 return Buffer.from(response.join(eol + eol) + eol, 'utf-8');
287 }
288
289 return encoding.convert(response.join(eol + eol) + eol, this._table.charset);
290 };