Debian Codegraph @

node/gettext-parser/lib/mocompiler.js

raw
1 import { Buffer } from 'node:buffer';
2 import encoding from 'encoding';
3 import { HEADERS, formatCharset, generateHeader, compareMsgid } 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 binary MO object
9 *
10 * @param {Object} table Translation object
11 * @return {Buffer} Compiled binary MO object
12 */
13 export default function (table) {
14 const compiler = new Compiler(table);
15
16 return compiler.compile();
17 };
18
19 /**
20 * Creates a MO compiler object.
21 *
22 * @constructor
23 * @param {Object} table Translation table as defined in the README
24 */
25 function Compiler (table = {}) {
26 this._table = table;
27
28 let { headers = {}, translations = {} } = this._table;
29
30 headers = Object.keys(headers).reduce((result, key) => {
31 const lowerKey = key.toLowerCase();
32
33 if (HEADERS.has(lowerKey)) {
34 // POT-Creation-Date is removed in MO (see https://savannah.gnu.org/bugs/?49654)
35 if (lowerKey !== 'pot-creation-date') {
36 result[HEADERS.get(lowerKey)] = headers[key];
37 }
38 } else {
39 result[key] = headers[key];
40 }
41
42 return result;
43 }, {});
44
45 // filter out empty translations
46 translations = Object.keys(translations).reduce((result, msgctxt) => {
47 const context = translations[msgctxt];
48 const msgs = Object.keys(context).reduce((result, msgid) => {
49 const hasTranslation = context[msgid].msgstr.some(item => !!item.length);
50
51 if (hasTranslation) {
52 result[msgid] = context[msgid];
53 }
54
55 return result;
56 }, {});
57
58 if (Object.keys(msgs).length) {
59 result[msgctxt] = msgs;
60 }
61
62 return result;
63 }, {});
64
65 this._table.translations = translations;
66 this._table.headers = headers;
67
68 this._translations = [];
69
70 this._writeFunc = 'writeUInt32LE';
71
72 this._handleCharset();
73 }
74
75 /**
76 * Magic bytes for the generated binary data
77 */
78 Compiler.prototype.MAGIC = 0x950412de;
79
80 /**
81 * Handles header values, replaces or adds (if needed) a charset property
82 */
83 Compiler.prototype._handleCharset = function () {
84 const ct = contentType.parse(this._table.headers['Content-Type'] || 'text/plain');
85
86 const charset = formatCharset(this._table.charset || ct.parameters.charset || 'utf-8');
87
88 // clean up content-type charset independently using fallback if missing
89 if (ct.parameters.charset) {
90 ct.parameters.charset = formatCharset(ct.parameters.charset);
91 }
92
93 this._table.charset = charset;
94 this._table.headers['Content-Type'] = contentType.format(ct);
95 };
96
97 /**
98 * Generates an array of translation strings
99 * in the form of [{msgid:... , msgstr:...}]
100 *
101 * @return {Array} Translation strings array
102 */
103 Compiler.prototype._generateList = function () {
104 const list = [];
105
106 list.push({
107 msgid: Buffer.alloc(0),
108 msgstr: encoding.convert(generateHeader(this._table.headers), this._table.charset)
109 });
110
111 Object.keys(this._table.translations).forEach(msgctxt => {
112 if (typeof this._table.translations[msgctxt] !== 'object') {
113 return;
114 }
115
116 Object.keys(this._table.translations[msgctxt]).forEach(msgid => {
117 if (typeof this._table.translations[msgctxt][msgid] !== 'object') {
118 return;
119 }
120
121 if (msgctxt === '' && msgid === '') {
122 return;
123 }
124
125 const msgidPlural = this._table.translations[msgctxt][msgid].msgid_plural;
126 let key = msgid;
127
128 if (msgctxt) {
129 key = msgctxt + '\u0004' + key;
130 }
131
132 if (msgidPlural) {
133 key += '\u0000' + msgidPlural;
134 }
135
136 const value = [].concat(this._table.translations[msgctxt][msgid].msgstr || []).join('\u0000');
137
138 list.push({
139 msgid: encoding.convert(key, this._table.charset),
140 msgstr: encoding.convert(value, this._table.charset)
141 });
142 });
143 });
144
145 return list;
146 };
147
148 /**
149 * Calculate buffer size for the final binary object
150 *
151 * @param {Array} list An array of translation strings from _generateList
152 * @return {Object} Size data of {msgid, msgstr, total}
153 */
154 Compiler.prototype._calculateSize = function (list) {
155 let msgidLength = 0;
156 let msgstrLength = 0;
157 let totalLength = 0;
158
159 list.forEach(translation => {
160 msgidLength += translation.msgid.length + 1; // + extra 0x00
161 msgstrLength += translation.msgstr.length + 1; // + extra 0x00
162 });
163
164 totalLength = 4 + // magic number
165 4 + // revision
166 4 + // string count
167 4 + // original string table offset
168 4 + // translation string table offset
169 4 + // hash table size
170 4 + // hash table offset
171 (4 + 4) * list.length + // original string table
172 (4 + 4) * list.length + // translations string table
173 msgidLength + // originals
174 msgstrLength; // translations
175
176 return {
177 msgid: msgidLength,
178 msgstr: msgstrLength,
179 total: totalLength
180 };
181 };
182
183 /**
184 * Generates the binary MO object from the translation list
185 *
186 * @param {Array} list translation list
187 * @param {Object} size Byte size information
188 * @return {Buffer} Compiled MO object
189 */
190 Compiler.prototype._build = function (list, size) {
191 const returnBuffer = Buffer.alloc(size.total);
192 let curPosition = 0;
193 let i;
194 let len;
195
196 // magic
197 returnBuffer[this._writeFunc](this.MAGIC, 0);
198
199 // revision
200 returnBuffer[this._writeFunc](0, 4);
201
202 // string count
203 returnBuffer[this._writeFunc](list.length, 8);
204
205 // original string table offset
206 returnBuffer[this._writeFunc](28, 12);
207
208 // translation string table offset
209 returnBuffer[this._writeFunc](28 + (4 + 4) * list.length, 16);
210
211 // hash table size
212 returnBuffer[this._writeFunc](0, 20);
213
214 // hash table offset
215 returnBuffer[this._writeFunc](28 + (4 + 4) * list.length * 2, 24);
216
217 // build originals table
218 curPosition = 28 + 2 * (4 + 4) * list.length;
219 for (i = 0, len = list.length; i < len; i++) {
220 list[i].msgid.copy(returnBuffer, curPosition);
221 returnBuffer[this._writeFunc](list[i].msgid.length, 28 + i * 8);
222 returnBuffer[this._writeFunc](curPosition, 28 + i * 8 + 4);
223 returnBuffer[curPosition + list[i].msgid.length] = 0x00;
224 curPosition += list[i].msgid.length + 1;
225 }
226
227 // build translations table
228 for (i = 0, len = list.length; i < len; i++) {
229 list[i].msgstr.copy(returnBuffer, curPosition);
230 returnBuffer[this._writeFunc](list[i].msgstr.length, 28 + (4 + 4) * list.length + i * 8);
231 returnBuffer[this._writeFunc](curPosition, 28 + (4 + 4) * list.length + i * 8 + 4);
232 returnBuffer[curPosition + list[i].msgstr.length] = 0x00;
233 curPosition += list[i].msgstr.length + 1;
234 }
235
236 return returnBuffer;
237 };
238
239 /**
240 * Compiles translation object into a binary MO object
241 *
242 * @return {Buffer} Compiled MO object
243 */
244 Compiler.prototype.compile = function () {
245 const list = this._generateList();
246 const size = this._calculateSize(list);
247
248 list.sort(compareMsgid);
249
250 return this._build(list, size);
251 };