@lingui/cli 3.15.0 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/build/LICENSE +21 -0
  3. package/build/api/catalog.js +582 -0
  4. package/build/api/compile.js +89 -0
  5. package/{api → build/api}/detect.js +23 -9
  6. package/build/api/extract.js +78 -0
  7. package/build/api/extractors/babel.js +51 -0
  8. package/build/api/extractors/index.js +51 -0
  9. package/build/api/extractors/typescript.js +71 -0
  10. package/build/api/formats/csv.js +65 -0
  11. package/{api → build/api}/formats/index.js +8 -5
  12. package/build/api/formats/lingui.js +67 -0
  13. package/build/api/formats/minimal.js +63 -0
  14. package/build/api/formats/po-gettext.js +296 -0
  15. package/build/api/formats/po.js +122 -0
  16. package/{api → build/api}/help.js +6 -18
  17. package/{api → build/api}/index.js +7 -7
  18. package/build/api/locales.js +45 -0
  19. package/{api → build/api}/pseudoLocalize.js +13 -13
  20. package/build/api/stats.js +46 -0
  21. package/{api → build/api}/utils.js +21 -40
  22. package/build/lingui-add-locale.js +11 -0
  23. package/build/lingui-compile.js +192 -0
  24. package/build/lingui-extract-template.js +64 -0
  25. package/build/lingui-extract.js +181 -0
  26. package/{lingui.js → build/lingui.js} +2 -2
  27. package/{services → build/services}/translationIO.js +78 -94
  28. package/build/tests.js +78 -0
  29. package/package.json +18 -12
  30. package/api/catalog.js +0 -778
  31. package/api/compile.js +0 -172
  32. package/api/extract.js +0 -192
  33. package/api/extractors/babel.js +0 -61
  34. package/api/extractors/index.js +0 -130
  35. package/api/extractors/typescript.js +0 -77
  36. package/api/formats/csv.js +0 -71
  37. package/api/formats/lingui.js +0 -64
  38. package/api/formats/minimal.js +0 -63
  39. package/api/formats/po-gettext.js +0 -331
  40. package/api/formats/po.js +0 -130
  41. package/api/locales.js +0 -43
  42. package/api/stats.js +0 -51
  43. package/lingui-add-locale.js +0 -11
  44. package/lingui-compile.js +0 -198
  45. package/lingui-extract-template.js +0 -123
  46. package/lingui-extract.js +0 -286
@@ -1,71 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.default = void 0;
9
-
10
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
11
-
12
- var _fs = _interopRequireDefault(require("fs"));
13
-
14
- var _papaparse = _interopRequireDefault(require("papaparse"));
15
-
16
- var _utils = require("../utils");
17
-
18
- var serialize = function serialize(catalog) {
19
- var rawArr = Object.keys(catalog).map(function (key) {
20
- return [key, catalog[key].translation];
21
- });
22
- return _papaparse.default.unparse(rawArr);
23
- };
24
-
25
- var deserialize = function deserialize(raw) {
26
- var rawCatalog = _papaparse.default.parse(raw);
27
-
28
- var messages = {};
29
-
30
- if (rawCatalog.errors.length) {
31
- throw new Error(rawCatalog.errors.map(function (err) {
32
- return JSON.stringify(err);
33
- }).join(";"));
34
- }
35
-
36
- rawCatalog.data.forEach(function (_ref) {
37
- var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
38
- key = _ref2[0],
39
- translation = _ref2[1];
40
-
41
- messages[key] = {
42
- translation: translation,
43
- obsolete: false,
44
- message: null,
45
- origin: []
46
- };
47
- });
48
- return messages;
49
- };
50
-
51
- var csv = {
52
- catalogExtension: ".csv",
53
- write: function write(filename, catalog) {
54
- var messages = serialize(catalog);
55
- (0, _utils.writeFileIfChanged)(filename, messages);
56
- },
57
- read: function read(filename) {
58
- var raw = _fs.default.readFileSync(filename).toString();
59
-
60
- try {
61
- return deserialize(raw);
62
- } catch (e) {
63
- throw new Error("Cannot read ".concat(filename, ": ").concat(e.message));
64
- }
65
- },
66
- parse: function parse(content) {
67
- return deserialize(content);
68
- }
69
- };
70
- var _default = csv;
71
- exports.default = _default;
@@ -1,64 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
6
-
7
- Object.defineProperty(exports, "__esModule", {
8
- value: true
9
- });
10
- exports.default = void 0;
11
-
12
- var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
13
-
14
- var _fs = _interopRequireDefault(require("fs"));
15
-
16
- var R = _interopRequireWildcard(require("ramda"));
17
-
18
- var _utils = require("../utils");
19
-
20
- var removeOrigins = R.map(function (_ref) {
21
- var origin = _ref.origin,
22
- message = (0, _objectWithoutProperties2.default)(_ref, ["origin"]);
23
- return message;
24
- });
25
- var removeLineNumbers = R.map(function (message) {
26
- if (message.origin) {
27
- message.origin.map(function (originValue) {
28
- originValue.pop();
29
- return originValue;
30
- });
31
- }
32
-
33
- return message;
34
- });
35
- var lingui = {
36
- catalogExtension: ".json",
37
- write: function write(filename, catalog, options) {
38
- var outputCatalog = catalog;
39
-
40
- if (options.origins === false) {
41
- outputCatalog = removeOrigins(catalog);
42
- }
43
-
44
- if (options.origins !== false && options.lineNumbers === false) {
45
- outputCatalog = removeLineNumbers(outputCatalog);
46
- }
47
-
48
- (0, _utils.writeFileIfChanged)(filename, JSON.stringify(outputCatalog, null, 2));
49
- },
50
- read: function read(filename) {
51
- var raw = _fs.default.readFileSync(filename).toString();
52
-
53
- try {
54
- return JSON.parse(raw);
55
- } catch (e) {
56
- throw new Error("Cannot read ".concat(filename, ": ").concat(e.message));
57
- }
58
- },
59
- parse: function parse(content) {
60
- return content;
61
- }
62
- };
63
- var _default = lingui;
64
- exports.default = _default;
@@ -1,63 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
6
-
7
- Object.defineProperty(exports, "__esModule", {
8
- value: true
9
- });
10
- exports.default = void 0;
11
-
12
- var _fs = _interopRequireDefault(require("fs"));
13
-
14
- var R = _interopRequireWildcard(require("ramda"));
15
-
16
- var serialize = R.map(function (message) {
17
- return message.translation || "";
18
- });
19
- var deserialize = R.map(function (translation) {
20
- return {
21
- translation: translation,
22
- obsolete: false,
23
- message: null,
24
- origin: []
25
- };
26
- });
27
- var minimal = {
28
- catalogExtension: ".json",
29
- write: function write(filename, catalog) {
30
- var _file;
31
-
32
- var messages = serialize(catalog);
33
- var file = null;
34
-
35
- try {
36
- file = _fs.default.readFileSync(filename, 'utf8');
37
- } catch (error) {
38
- if (error.code !== "ENOENT") {
39
- throw error;
40
- }
41
- }
42
-
43
- var shouldUseTrailingNewline = file === null || ((_file = file) === null || _file === void 0 ? void 0 : _file.endsWith("\n"));
44
- var trailingNewLine = shouldUseTrailingNewline ? "\n" : "";
45
-
46
- _fs.default.writeFileSync(filename, "".concat(JSON.stringify(messages, null, 2)).concat(trailingNewLine));
47
- },
48
- read: function read(filename) {
49
- var raw = _fs.default.readFileSync(filename).toString();
50
-
51
- try {
52
- var rawCatalog = JSON.parse(raw);
53
- return deserialize(rawCatalog);
54
- } catch (e) {
55
- throw new Error("Cannot read ".concat(filename, ": ").concat(e.message));
56
- }
57
- },
58
- parse: function parse(content) {
59
- return deserialize(content);
60
- }
61
- };
62
- var _default = minimal;
63
- exports.default = _default;
@@ -1,331 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
6
-
7
- Object.defineProperty(exports, "__esModule", {
8
- value: true
9
- });
10
- exports.default = void 0;
11
-
12
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
13
-
14
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
15
-
16
- var _dateFns = require("date-fns");
17
-
18
- var _fs = _interopRequireDefault(require("fs"));
19
-
20
- var _messageformatParser = _interopRequireDefault(require("messageformat-parser"));
21
-
22
- var _pluralsCldr = _interopRequireDefault(require("plurals-cldr"));
23
-
24
- var _pofile = _interopRequireDefault(require("pofile"));
25
-
26
- var R = _interopRequireWildcard(require("ramda"));
27
-
28
- var _plurals = _interopRequireDefault(require("node-gettext/lib/plurals"));
29
-
30
- var _utils = require("../utils");
31
-
32
- function getCreateHeaders() {
33
- var language = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "no";
34
- return {
35
- "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),
36
- "MIME-Version": "1.0",
37
- "Content-Type": "text/plain; charset=utf-8",
38
- "Content-Transfer-Encoding": "8bit",
39
- "X-Generator": "@lingui/cli",
40
- Language: language
41
- };
42
- } // Attempts to turn a single tokenized ICU plural case back into a string.
43
-
44
-
45
- function stringifyICUCase(icuCase) {
46
- return icuCase.tokens.map(function (token) {
47
- if (typeof token === "string") {
48
- return token;
49
- } else if (token.type === "octothorpe") {
50
- return "#";
51
- } else if (token.type === "argument") {
52
- return "{" + token.arg + "}";
53
- } else {
54
- console.warn("Unexpected token \"".concat(token, "\" while stringifying plural case \"").concat(icuCase, "\". Token will be ignored."));
55
- return "";
56
- }
57
- }).join("");
58
- }
59
-
60
- var ICU_PLURAL_REGEX = /^{.*, plural, .*}$/;
61
- var ICU_SELECT_REGEX = /^{.*, select(Ordinal)?, .*}$/;
62
- var LINE_ENDINGS = /\r?\n/g; // Prefix that is used to identitify context information used by this module in PO's "extracted comments".
63
-
64
- var CTX_PREFIX = "js-lingui:";
65
-
66
- var serialize = function serialize(items, options) {
67
- return R.compose(R.values, R.mapObjIndexed(function (message, key) {
68
- var _message$extractedCom;
69
-
70
- var item = new _pofile.default.Item();
71
- item.msgid = key;
72
- item.comments = message.comments || []; // The extractedComments array may be modified in this method, so create a new array with the message's elements.
73
- // Destructuring `undefined` is forbidden, so fallback to `[]` if the message has no extracted comments.
74
-
75
- item.extractedComments = (0, _toConsumableArray2.default)((_message$extractedCom = message.extractedComments) !== null && _message$extractedCom !== void 0 ? _message$extractedCom : []);
76
-
77
- if (message.context) {
78
- item.msgctxt = message.context;
79
- }
80
-
81
- if (options.origins !== false) {
82
- if (message.origin && options.lineNumbers === false) {
83
- item.references = message.origin.map(function (_ref) {
84
- var _ref2 = (0, _slicedToArray2.default)(_ref, 1),
85
- path = _ref2[0];
86
-
87
- return path;
88
- });
89
- } else {
90
- item.references = message.origin ? message.origin.map(_utils.joinOrigin) : [];
91
- }
92
- } // @ts-ignore: Figure out how to set this flag
93
-
94
-
95
- item.obsolete = message.obsolete;
96
- item.flags = message.flags ? R.fromPairs(message.flags.map(function (flag) {
97
- return [flag, true];
98
- })) : {}; // Depending on whether custom ids are used by the developer, the (potential plural) "original", untranslated ICU
99
- // message can be found in `message.message` or in the item's `key` itself.
100
-
101
- var icuMessage = message.message || key;
102
-
103
- var _simplifiedMessage = icuMessage.replace(LINE_ENDINGS, " "); // Quick check to see if original message is a plural localization.
104
-
105
-
106
- if (ICU_PLURAL_REGEX.test(_simplifiedMessage)) {
107
- try {
108
- var _message$translation;
109
-
110
- var _ICUParser$parse = _messageformatParser.default.parse(icuMessage),
111
- _ICUParser$parse2 = (0, _slicedToArray2.default)(_ICUParser$parse, 1),
112
- messageAst = _ICUParser$parse2[0]; // Check if any of the plural cases contain plurals themselves.
113
-
114
-
115
- if (messageAst.cases.some(function (icuCase) {
116
- return icuCase.tokens.some(function (token) {
117
- return token.type === "plural";
118
- });
119
- })) {
120
- console.warn("Nested plurals cannot be expressed with gettext plurals. " + "Message with key \"%s\" will not be saved correctly.", key);
121
- } // Store placeholder that is pluralized upon to allow restoring ICU format later.
122
-
123
-
124
- var ctx = new URLSearchParams({
125
- pluralize_on: messageAst.arg
126
- });
127
-
128
- if (message.message == null) {
129
- // For messages without developer-set ID, use first case as `msgid` and the last case as `msgid_plural`.
130
- // This does not necessarily make sense for development languages with more than two numbers, but gettext
131
- // only supports exactly two plural forms.
132
- item.msgid = stringifyICUCase(messageAst.cases[0]);
133
- item.msgid_plural = stringifyICUCase(messageAst.cases[messageAst.cases.length - 1]); // Since the original msgid is overwritten, store ICU message to allow restoring that ID later.
134
-
135
- ctx.set("icu", key);
136
- } else {
137
- // For messages with developer-set ID, append `_plural` to the key to generate `msgid_plural`.
138
- item.msgid_plural = key + "_plural";
139
- }
140
-
141
- ctx.sort();
142
- item.extractedComments.push(CTX_PREFIX + ctx.toString()); // If there is a translated value, parse that instead of the original message to prevent overriding localized
143
- // content with the original message. If there is no translated value, don't touch msgstr, since marking item as
144
- // plural (above) already causes `pofile` to automatically generate `msgstr[0]` and `msgstr[1]`.
145
-
146
- if (((_message$translation = message.translation) === null || _message$translation === void 0 ? void 0 : _message$translation.length) > 0) {
147
- try {
148
- var _ICUParser$parse3 = _messageformatParser.default.parse(message.translation),
149
- _ICUParser$parse4 = (0, _slicedToArray2.default)(_ICUParser$parse3, 1),
150
- ast = _ICUParser$parse4[0];
151
-
152
- if (ast.cases == null) {
153
- console.warn("Found translation without plural cases for key \"".concat(key, "\". ") + "This likely means that a translated .po file misses multiple msgstr[] entries for the key. " + "Translation found: \"".concat(message.translation, "\""));
154
- item.msgstr = [message.translation];
155
- } else {
156
- item.msgstr = ast.cases.map(stringifyICUCase);
157
- }
158
- } catch (e) {
159
- console.error("Error parsing translation ICU for key \"".concat(key, "\""), e);
160
- }
161
- }
162
- } catch (e) {
163
- console.error("Error parsing message ICU for key \"".concat(key, "\":"), e);
164
- }
165
- } else {
166
- if (!options.disableSelectWarning && ICU_SELECT_REGEX.test(_simplifiedMessage)) {
167
- console.warn("ICU 'select' and 'selectOrdinal' formats cannot be expressed natively in gettext format. " + "Item with key \"%s\" will be included in the catalog as raw ICU message. " + "To disable this warning, include '{ disableSelectWarning: true }' in the config's 'formatOptions'", key);
168
- }
169
-
170
- item.msgstr = [message.translation];
171
- }
172
-
173
- return item;
174
- }))(items);
175
- };
176
-
177
- var getMessageKey = R.prop("msgid");
178
- var getTranslations = R.prop("msgstr");
179
- var getExtractedComments = R.prop("extractedComments");
180
- var getTranslatorComments = R.prop("comments");
181
- var getMessageContext = R.prop("msgctxt");
182
- var getOrigins = R.prop("references");
183
- var getFlags = R.compose(R.map(R.trim), R.keys, R.dissoc("obsolete"), // backward-compatibility, remove in 3.x
184
- R.prop("flags"));
185
- var isObsolete = R.either(R.path(["flags", "obsolete"]), R.prop("obsolete"));
186
- var getTranslationCount = R.compose(R.length, getTranslations);
187
- var deserialize = R.map(R.applySpec({
188
- translation: R.compose(R.head, R.defaultTo([]), getTranslations),
189
- extractedComments: R.compose(R.defaultTo([]), getExtractedComments),
190
- comments: R.compose(R.defaultTo([]), getTranslatorComments),
191
- context: R.compose(R.defaultTo(null), getMessageContext),
192
- obsolete: isObsolete,
193
- origin: R.compose(R.map(_utils.splitOrigin), R.defaultTo([]), getOrigins),
194
- flags: getFlags
195
- }));
196
- /**
197
- * Returns ICU case labels in the order that gettext lists localized messages, e.g. 0,1,2 => `["one", "two", "other"]`.
198
- *
199
- * Obtaining the ICU case labels for gettext-supported inputs (gettext doesn't support fractions, even though some
200
- * languages have a separate case for fractional numbers) works by applying the CLDR selector to the example values
201
- * listed in the node-gettext plurals module.
202
- *
203
- * This approach is heavily influenced by
204
- * https://github.com/LLK/po2icu/blob/9eb97f81f72b2fee02b77f1424702e019647e9b9/lib/po2icu.js#L148.
205
- */
206
-
207
- var getPluralCases = function getPluralCases(lang) {
208
- // If users uses locale with underscore or slash, es-ES, es_ES, gettextplural is "es" not es-ES.
209
- var _lang$split = lang.split(/[-_]/g),
210
- _lang$split2 = (0, _slicedToArray2.default)(_lang$split, 1),
211
- correctLang = _lang$split2[0];
212
-
213
- var gettextPluralsInfo = _plurals.default[correctLang];
214
- return gettextPluralsInfo === null || gettextPluralsInfo === void 0 ? void 0 : gettextPluralsInfo.examples.map(function (pluralCase) {
215
- return (0, _pluralsCldr.default)(correctLang, pluralCase.sample);
216
- });
217
- };
218
-
219
- var convertPluralsToICU = function convertPluralsToICU(items, lang) {
220
- // .po plurals are numbered 0-N and need to be mapped to ICU plural classes ("one", "few", "many"...). Different
221
- // languages can have different plural classes (some start with "zero", some with "one"), so read that data from CLDR.
222
- // `pluralForms` may be `null` if lang is not found. As long as no plural is used, don't report an error.
223
- var pluralForms = getPluralCases(lang);
224
- items.forEach(function (item) {
225
- var _item$extractedCommen;
226
-
227
- var translationCount = getTranslationCount(item);
228
- var messageKey = getMessageKey(item); // Messages without multiple translations (= plural cases) need no further processing.
229
-
230
- if (translationCount <= 1 && !item.msgid_plural) {
231
- return;
232
- } // msgid_plural must be set, but its actual value is not important.
233
-
234
-
235
- if (!item.msgid_plural) {
236
- console.warn("Multiple translations for item with key \"%s\" but missing 'msgid_plural' in catalog \"".concat(lang, "\". This is not supported and the plural cases will be ignored."), messageKey);
237
- return;
238
- }
239
-
240
- var contextComment = (_item$extractedCommen = item.extractedComments.find(function (comment) {
241
- return comment.startsWith(CTX_PREFIX);
242
- })) === null || _item$extractedCommen === void 0 ? void 0 : _item$extractedCommen.substr(CTX_PREFIX.length);
243
- var ctx = new URLSearchParams(contextComment);
244
-
245
- if (contextComment != null) {
246
- item.extractedComments = item.extractedComments.filter(function (comment) {
247
- return !comment.startsWith(CTX_PREFIX);
248
- });
249
- } // If an original ICU was stored, use that as `msgid` to match the catalog that was originally exported.
250
-
251
-
252
- var storedICU = ctx.get("icu");
253
-
254
- if (storedICU != null) {
255
- item.msgid = storedICU;
256
- } // If all translations are empty, ignore item.
257
-
258
-
259
- if (item.msgstr.every(function (str) {
260
- return str.length === 0;
261
- })) {
262
- return;
263
- }
264
-
265
- if (pluralForms == null) {
266
- console.warn("Multiple translations for item with key \"%s\"\xA0in language \"".concat(lang, "\", but no plural cases were found. ") + "This prohibits the translation of .po plurals into ICU plurals. Pluralization will not work for this key.", messageKey);
267
- return;
268
- }
269
-
270
- var pluralCount = pluralForms.length;
271
-
272
- if (translationCount > pluralCount) {
273
- console.warn("More translations provided (".concat(translationCount, ") for item with key \"%s\" in language \"").concat(lang, "\" than there are plural cases available (").concat(pluralCount, "). ") + "This will result in not all translations getting picked up.", messageKey);
274
- } // Map each msgstr to a "<pluralform> {<translated_string>}" entry, joined by one space.
275
-
276
-
277
- var pluralClauses = item.msgstr.map(function (str, index) {
278
- return pluralForms[index] + " {" + str + "}";
279
- }).join(" "); // Find out placeholder name from item's message context, defaulting to "count".
280
-
281
- var pluralizeOn = ctx.get("pluralize_on");
282
-
283
- if (!pluralizeOn) {
284
- console.warn("Unable to determine plural placeholder name for item with key \"%s\" in language \"".concat(lang, "\" (should be stored in a comment starting with \"#. ").concat(CTX_PREFIX, "\"), assuming \"count\"."), messageKey);
285
- pluralizeOn = "count";
286
- }
287
-
288
- item.msgstr = ["{" + pluralizeOn + ", plural, " + pluralClauses + "}"];
289
- });
290
- };
291
-
292
- var indexItems = R.indexBy(getMessageKey);
293
- var poGettext = {
294
- catalogExtension: ".po",
295
- write: function write(filename, catalog, options) {
296
- var po;
297
-
298
- if (_fs.default.existsSync(filename)) {
299
- var _raw = _fs.default.readFileSync(filename).toString();
300
-
301
- po = _pofile.default.parse(_raw);
302
- } else {
303
- po = new _pofile.default();
304
- po.headers = getCreateHeaders(options.locale);
305
-
306
- if (options.locale === undefined) {
307
- delete po.headers.Language;
308
- }
309
-
310
- po.headerOrder = Object.keys(po.headers);
311
- }
312
-
313
- po.items = this.serialize(catalog, options);
314
- (0, _utils.writeFileIfChanged)(filename, po.toString());
315
- },
316
- // Mainly exported for easier testing
317
- serialize: serialize,
318
- read: function read(filename) {
319
- var raw = _fs.default.readFileSync(filename).toString();
320
-
321
- return this.parse(raw);
322
- },
323
- parse: function parse(raw) {
324
- var po = _pofile.default.parse(raw);
325
-
326
- convertPluralsToICU(po.items, po.headers.Language);
327
- return deserialize(indexItems(po.items));
328
- }
329
- };
330
- var _default = poGettext;
331
- exports.default = _default;
package/api/formats/po.js DELETED
@@ -1,130 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
4
-
5
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
6
-
7
- Object.defineProperty(exports, "__esModule", {
8
- value: true
9
- });
10
- exports.default = void 0;
11
-
12
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
13
-
14
- var _fs = _interopRequireDefault(require("fs"));
15
-
16
- var R = _interopRequireWildcard(require("ramda"));
17
-
18
- var _dateFns = require("date-fns");
19
-
20
- var _pofile = _interopRequireDefault(require("pofile"));
21
-
22
- var _utils = require("../utils");
23
-
24
- var getCreateHeaders = function getCreateHeaders() {
25
- var language = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "no";
26
- return {
27
- "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),
28
- "MIME-Version": "1.0",
29
- "Content-Type": "text/plain; charset=utf-8",
30
- "Content-Transfer-Encoding": "8bit",
31
- "X-Generator": "@lingui/cli",
32
- Language: language
33
- };
34
- };
35
-
36
- var serialize = function serialize(items, options) {
37
- return R.compose(R.values, R.mapObjIndexed(function (message, key) {
38
- var item = new _pofile.default.Item();
39
- item.msgid = key;
40
- item.msgstr = [message.translation];
41
- item.comments = message.comments || [];
42
- item.extractedComments = message.extractedComments || [];
43
-
44
- if (message.context) {
45
- item.msgctxt = message.context;
46
- }
47
-
48
- if (options.origins !== false) {
49
- if (message.origin && options.lineNumbers === false) {
50
- item.references = message.origin.map(function (_ref) {
51
- var _ref2 = (0, _slicedToArray2.default)(_ref, 1),
52
- path = _ref2[0];
53
-
54
- return path;
55
- });
56
- } else {
57
- item.references = message.origin ? message.origin.map(_utils.joinOrigin) : [];
58
- }
59
- } // @ts-ignore: Figure out how to set this flag
60
-
61
-
62
- item.obsolete = message.obsolete;
63
- item.flags = message.flags ? R.fromPairs(message.flags.map(function (flag) {
64
- return [flag, true];
65
- })) : {};
66
- return item;
67
- }))(items);
68
- };
69
-
70
- var getMessageKey = R.prop("msgid");
71
- var getTranslations = R.prop("msgstr");
72
- var getExtractedComments = R.prop("extractedComments");
73
- var getTranslatorComments = R.prop("comments");
74
- var getMessageContext = R.prop("msgctxt");
75
- var getOrigins = R.prop("references");
76
- var getFlags = R.compose(R.map(R.trim), R.keys, R.dissoc("obsolete"), // backward-compatibility, remove in 3.x
77
- R.prop("flags"));
78
- var isObsolete = R.either(R.path(["flags", "obsolete"]), R.prop("obsolete"));
79
- var deserialize = R.map(R.applySpec({
80
- translation: R.compose(R.head, R.defaultTo([]), getTranslations),
81
- extractedComments: R.compose(R.defaultTo([]), getExtractedComments),
82
- comments: R.compose(R.defaultTo([]), getTranslatorComments),
83
- context: R.compose(R.defaultTo(null), getMessageContext),
84
- obsolete: isObsolete,
85
- origin: R.compose(R.map(_utils.splitOrigin), R.defaultTo([]), getOrigins),
86
- flags: getFlags
87
- }));
88
- var validateItems = R.forEach(function (item) {
89
- if (R.length(getTranslations(item)) > 1) {
90
- console.warn("Multiple translations for item with key %s is not supported and it will be ignored.", getMessageKey(item));
91
- }
92
- });
93
- var indexItems = R.indexBy(getMessageKey);
94
- var po = {
95
- catalogExtension: ".po",
96
- write: function write(filename, catalog, options) {
97
- var po;
98
-
99
- if (_fs.default.existsSync(filename)) {
100
- var _raw = _fs.default.readFileSync(filename).toString();
101
-
102
- po = _pofile.default.parse(_raw);
103
- } else {
104
- po = new _pofile.default();
105
- po.headers = getCreateHeaders(options.locale);
106
-
107
- if (options.locale === undefined) {
108
- delete po.headers.Language;
109
- }
110
-
111
- po.headerOrder = R.keys(po.headers);
112
- }
113
-
114
- po.items = serialize(catalog, options);
115
- (0, _utils.writeFileIfChanged)(filename, po.toString());
116
- },
117
- read: function read(filename) {
118
- var raw = _fs.default.readFileSync(filename).toString();
119
-
120
- return this.parse(raw);
121
- },
122
- parse: function parse(raw) {
123
- var po = _pofile.default.parse(raw);
124
-
125
- validateItems(po.items);
126
- return deserialize(indexItems(po.items));
127
- }
128
- };
129
- var _default = po;
130
- exports.default = _default;