@vendure/ngx-translate-extract
Version:
Extract strings from projects using ngx-translate
56 lines (55 loc) • 2.05 kB
JavaScript
import { po } from 'gettext-parser';
import { TranslationCollection } from '../utils/translation.collection.js';
export class PoCompiler {
extension = 'po';
domain = '';
includeSources = true;
constructor(options) {
this.includeSources = options?.poSourceLocation ?? true;
}
compile(collection) {
const data = {
charset: 'utf-8',
headers: {
'mime-version': '1.0',
'content-type': 'text/plain; charset=utf-8',
'content-transfer-encoding': '8bit'
},
translations: {
[this.domain]: Object.keys(collection.values)
.reduce((translations, key) => {
const entry = collection.get(key);
const comments = this.includeSources ? { reference: entry.sourceFiles?.join('\n') } : undefined;
return {
...translations,
[key]: {
msgid: key,
msgstr: entry.value,
comments: comments
}
};
}, {})
}
};
return po.compile(data, {}).toString('utf8');
}
parse(contents) {
const parsedPo = po.parse(contents, { defaultCharset: 'utf8' });
const poTranslations = parsedPo.translations?.[this.domain];
if (!poTranslations) {
return new TranslationCollection();
}
const translationEntries = Object.entries(poTranslations);
const convertedTranslations = {};
for (const [msgid, message] of translationEntries) {
if (msgid === this.domain) {
continue;
}
convertedTranslations[msgid] = {
value: message.msgstr.at(-1),
sourceFiles: message.comments?.reference?.split('\n') || []
};
}
return new TranslationCollection(convertedTranslations);
}
}