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