@lingui/cli 4.0.0-next.4 → 4.0.0-next.5

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 (68) hide show
  1. package/dist/api/catalog/extractFromFiles.js +64 -0
  2. package/dist/api/catalog/getCatalogs.js +137 -0
  3. package/dist/api/catalog/getTranslationsForCatalog.js +68 -0
  4. package/dist/api/catalog/mergeCatalog.js +86 -0
  5. package/dist/api/catalog.js +286 -0
  6. package/dist/api/compile.js +115 -0
  7. package/dist/api/extractors/babel.js +158 -0
  8. package/dist/api/extractors/index.js +44 -0
  9. package/dist/api/extractors/typescript.js +15 -0
  10. package/dist/api/formats/formatterWrapper.js +48 -0
  11. package/dist/api/formats/index.js +95 -0
  12. package/dist/api/help.js +41 -0
  13. package/dist/api/index.js +31 -0
  14. package/dist/api/pseudoLocalize.js +60 -0
  15. package/dist/api/rethrownError.js +16 -0
  16. package/dist/api/stats.js +73 -0
  17. package/{build → dist}/api/types.js +2 -3
  18. package/dist/api/utils.js +117 -0
  19. package/dist/extract-experimental/buildExternalizeFilter.js +83 -0
  20. package/dist/extract-experimental/bundleSource.js +127 -0
  21. package/dist/extract-experimental/constants.js +16 -0
  22. package/dist/extract-experimental/getEntryPoints.js +20 -0
  23. package/dist/extract-experimental/getExperimentalCatalogs.js +30 -0
  24. package/dist/extract-experimental/resolveCatalogPath.js +34 -0
  25. package/dist/extract-experimental/resolveTemplatePath.js +19 -0
  26. package/dist/extract-experimental/writeCatalogs.js +54 -0
  27. package/dist/lingui-compile.js +158 -0
  28. package/dist/lingui-extract-experimental.js +113 -0
  29. package/dist/lingui-extract-template.js +52 -0
  30. package/dist/lingui-extract.js +192 -0
  31. package/dist/lingui.js +8 -0
  32. package/dist/services/translationIO.js +261 -0
  33. package/dist/tests.js +137 -0
  34. package/package.json +19 -13
  35. package/build/LICENSE +0 -21
  36. package/build/api/catalog/extractFromFiles.js +0 -45
  37. package/build/api/catalog/getCatalogs.js +0 -138
  38. package/build/api/catalog/getTranslationsForCatalog.js +0 -77
  39. package/build/api/catalog/mergeCatalog.js +0 -44
  40. package/build/api/catalog.js +0 -245
  41. package/build/api/compile.js +0 -72
  42. package/build/api/extractors/babel.js +0 -92
  43. package/build/api/extractors/index.js +0 -36
  44. package/build/api/extractors/typescript.js +0 -14
  45. package/build/api/formats/formatterWrapper.js +0 -45
  46. package/build/api/formats/index.js +0 -57
  47. package/build/api/generateMessageId.js +0 -12
  48. package/build/api/help.js +0 -42
  49. package/build/api/index.js +0 -58
  50. package/build/api/pseudoLocalize.js +0 -60
  51. package/build/api/rethrownError.js +0 -14
  52. package/build/api/stats.js +0 -40
  53. package/build/api/utils.js +0 -117
  54. package/build/extract-experimental/buildExternalizeFilter.js +0 -39
  55. package/build/extract-experimental/bundleSource.js +0 -69
  56. package/build/extract-experimental/constants.js +0 -10
  57. package/build/extract-experimental/getEntryPoints.js +0 -14
  58. package/build/extract-experimental/getExperimentalCatalogs.js +0 -28
  59. package/build/extract-experimental/resolveCatalogPath.js +0 -23
  60. package/build/extract-experimental/resolveTemplatePath.js +0 -17
  61. package/build/extract-experimental/writeCatalogs.js +0 -59
  62. package/build/lingui-compile.js +0 -156
  63. package/build/lingui-extract-experimental.js +0 -103
  64. package/build/lingui-extract-template.js +0 -46
  65. package/build/lingui-extract.js +0 -143
  66. package/build/lingui.js +0 -6
  67. package/build/services/translationIO.js +0 -266
  68. package/build/tests.js +0 -133
@@ -1,77 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getTranslationsForCatalog = getTranslationsForCatalog;
7
- async function getTranslationsForCatalog(catalog, locale, options) {
8
- const catalogs = await catalog.readAll();
9
- const template = (await catalog.readTemplate()) || {};
10
- const sourceLocaleCatalog = catalogs[options.sourceLocale] || {};
11
- const input = {
12
- ...template,
13
- ...sourceLocaleCatalog,
14
- ...catalogs[locale]
15
- };
16
- return Object.keys(input).reduce((acc, key) => {
17
- acc[key] = getTranslation(catalogs, input[key], locale, key, options);
18
- return acc;
19
- }, {});
20
- }
21
- function sourceLocaleFallback(catalog, key) {
22
- if (!(catalog !== null && catalog !== void 0 && catalog[key])) {
23
- return null;
24
- }
25
- return catalog[key].translation || catalog[key].message;
26
- }
27
- function getTranslation(catalogs, msg, locale, key, options) {
28
- const {
29
- fallbackLocales,
30
- sourceLocale,
31
- onMissing
32
- } = options;
33
- const getTranslation = _locale => {
34
- var _localeCatalog$key;
35
- const localeCatalog = catalogs[_locale];
36
- return localeCatalog === null || localeCatalog === void 0 ? void 0 : (_localeCatalog$key = localeCatalog[key]) === null || _localeCatalog$key === void 0 ? void 0 : _localeCatalog$key.translation;
37
- };
38
- const getMultipleFallbacks = _locale => {
39
- const fL = fallbackLocales && (fallbackLocales === null || fallbackLocales === void 0 ? void 0 : fallbackLocales[_locale]);
40
-
41
- // some probably the fallback will be undefined, so just search by locale
42
- if (!fL) return null;
43
- if (Array.isArray(fL)) {
44
- for (const fallbackLocale of fL) {
45
- if (catalogs[fallbackLocale] && getTranslation(fallbackLocale)) {
46
- return getTranslation(fallbackLocale);
47
- }
48
- }
49
- } else {
50
- return getTranslation(fL);
51
- }
52
- };
53
-
54
- // target locale -> fallback locales -> fallback locales default ->
55
- // ** (following fallbacks would emit `missing` warning) **
56
- // -> source locale translation -> source locale message
57
- // -> template message
58
- // ** last resort **
59
- // -> id
60
-
61
- let translation =
62
- // Get translation in target locale
63
- getTranslation(locale) ||
64
- // We search in fallbackLocales as dependent of each locale
65
- getMultipleFallbacks(locale) ||
66
- // Get translation in fallbackLocales.default (if any)
67
- (fallbackLocales === null || fallbackLocales === void 0 ? void 0 : fallbackLocales.default) && getTranslation(fallbackLocales.default) || sourceLocale && sourceLocale === locale && sourceLocaleFallback(catalogs[sourceLocale], key);
68
- if (!translation) {
69
- onMissing && onMissing({
70
- id: key,
71
- source: msg.message || sourceLocaleFallback(catalogs[sourceLocale], key)
72
- });
73
- }
74
- return translation || sourceLocale && sourceLocaleFallback(catalogs[sourceLocale], key) ||
75
- // take from template
76
- msg.message || key;
77
- }
@@ -1,44 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.mergeCatalog = mergeCatalog;
7
- var R = _interopRequireWildcard(require("ramda"));
8
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
9
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
10
- function mergeCatalog(prevCatalog, nextCatalog, forSourceLocale, options) {
11
- const nextKeys = Object.keys(nextCatalog);
12
- const prevKeys = R.keys(prevCatalog).map(String);
13
- const newKeys = R.difference(nextKeys, prevKeys);
14
- const mergeKeys = R.intersection(nextKeys, prevKeys);
15
- const obsoleteKeys = R.difference(prevKeys, nextKeys);
16
-
17
- // Initialize new catalog with new keys
18
- const newMessages = R.mapObjIndexed((message, key) => ({
19
- translation: forSourceLocale ? message.message || key : "",
20
- ...message
21
- }), R.pick(newKeys, nextCatalog));
22
-
23
- // Merge translations from previous catalog
24
- const mergedMessages = mergeKeys.map(key => {
25
- const updateFromDefaults = forSourceLocale && (prevCatalog[key].translation === prevCatalog[key].message || options.overwrite);
26
- const translation = updateFromDefaults ? nextCatalog[key].message || key : prevCatalog[key].translation;
27
- return {
28
- [key]: {
29
- translation,
30
- ...R.omit(["obsolete, translation"], nextCatalog[key])
31
- }
32
- };
33
- });
34
-
35
- // Mark all remaining translations as obsolete
36
- // Only if *options.files* is not provided
37
- const obsoleteMessages = obsoleteKeys.map(key => ({
38
- [key]: {
39
- ...prevCatalog[key],
40
- obsolete: !options.files
41
- }
42
- }));
43
- return R.mergeAll([newMessages, ...mergedMessages, ...obsoleteMessages]);
44
- }
@@ -1,245 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.cleanObsolete = exports.Catalog = void 0;
7
- exports.order = order;
8
- exports.orderByMessage = orderByMessage;
9
- var _fs = _interopRequireDefault(require("fs"));
10
- var _path = _interopRequireDefault(require("path"));
11
- var R = _interopRequireWildcard(require("ramda"));
12
- var _glob = _interopRequireDefault(require("glob"));
13
- var _normalizePath = _interopRequireDefault(require("normalize-path"));
14
- var _getTranslationsForCatalog = require("./catalog/getTranslationsForCatalog");
15
- var _mergeCatalog = require("./catalog/mergeCatalog");
16
- var _extractFromFiles = require("./catalog/extractFromFiles");
17
- var _utils = require("./utils");
18
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
20
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
- const LOCALE = "{locale}";
22
- const LOCALE_SUFFIX_RE = /\{locale\}.*$/;
23
- class Catalog {
24
- constructor({
25
- name,
26
- path,
27
- include,
28
- templatePath,
29
- format,
30
- exclude = []
31
- }, config) {
32
- this.config = config;
33
- this.name = name;
34
- this.path = (0, _utils.normalizeRelativePath)(path);
35
- this.include = include.map(_utils.normalizeRelativePath);
36
- this.exclude = [this.localeDir, ...exclude.map(_utils.normalizeRelativePath)];
37
- this.format = format;
38
- this.templateFile = templatePath || getTemplatePath(this.format.getTemplateExtension(), this.path);
39
- }
40
- async make(options) {
41
- const nextCatalog = await this.collect({
42
- files: options.files
43
- });
44
- if (!nextCatalog) return false;
45
- const prevCatalogs = await this.readAll();
46
- const catalogs = this.merge(prevCatalogs, nextCatalog, {
47
- overwrite: options.overwrite,
48
- files: options.files
49
- });
50
-
51
- // Map over all locales and post-process each catalog
52
- const cleanAndSort = R.map(R.pipe(
53
- // Clean obsolete messages
54
- options.clean ? cleanObsolete : R.identity,
55
- // Sort messages
56
- order(options.orderBy)));
57
- const sortedCatalogs = cleanAndSort(catalogs);
58
- const locales = options.locale ? [options.locale] : this.locales;
59
- await Promise.all(locales.map(locale => this.write(locale, sortedCatalogs[locale])));
60
- return sortedCatalogs;
61
- }
62
- async makeTemplate(options) {
63
- const catalog = await this.collect({
64
- files: options.files
65
- });
66
- if (!catalog) return false;
67
- const sorted = order(options.orderBy)(catalog);
68
- await this.writeTemplate(sorted);
69
- return sorted;
70
- }
71
-
72
- /**
73
- * Collect messages from source paths. Return a raw message catalog as JSON.
74
- */
75
- async collect(options = {}) {
76
- let paths = this.sourcePaths;
77
- if (options.files) {
78
- options.files = options.files.map(p => (0, _normalizePath.default)(p, false));
79
- const regex = new RegExp(options.files.join("|"), "i");
80
- paths = paths.filter(path => regex.test(path));
81
- }
82
- return await (0, _extractFromFiles.extractFromFiles)(paths, this.config);
83
- }
84
-
85
- /*
86
- *
87
- * prevCatalogs - map of message catalogs in all available languages with translations
88
- * nextCatalog - language-agnostic catalog with collected messages
89
- *
90
- * Note: if a catalog in prevCatalogs is null it means the language is available, but
91
- * no previous catalog was generated (usually first run).
92
- *
93
- * Orthogonal use-cases
94
- * --------------------
95
- *
96
- * Message IDs:
97
- * - auto-generated IDs: message is used as a key, `defaults` is not set
98
- * - custom IDs: message is used as `defaults`, custom ID as a key
99
- *
100
- * Source locale (defined by `sourceLocale` in config):
101
- * - catalog for `sourceLocale`: initially, `translation` is prefilled with `defaults`
102
- * (for custom IDs) or `key` (for auto-generated IDs)
103
- * - all other languages: translation is kept empty
104
- */
105
- merge(prevCatalogs, nextCatalog, options) {
106
- return R.mapObjIndexed((prevCatalog, locale) => {
107
- return (0, _mergeCatalog.mergeCatalog)(prevCatalog, nextCatalog, this.config.sourceLocale === locale, options);
108
- }, prevCatalogs);
109
- }
110
- async getTranslations(locale, options) {
111
- return await (0, _getTranslationsForCatalog.getTranslationsForCatalog)(this, locale, options);
112
- }
113
- async write(locale, messages) {
114
- const filename = (0, _utils.replacePlaceholders)(this.path, {
115
- locale
116
- }) + this.format.getCatalogExtension();
117
- const created = !_fs.default.existsSync(filename);
118
- await this.format.write(filename, messages, locale);
119
- return [created, filename];
120
- }
121
- async writeTemplate(messages) {
122
- const filename = this.templateFile;
123
- await this.format.write(filename, messages, undefined);
124
- }
125
- async writeCompiled(locale, compiledCatalog, namespace) {
126
- let ext;
127
- if (namespace === "es") {
128
- ext = "mjs";
129
- } else if (namespace === "ts") {
130
- ext = "ts";
131
- } else {
132
- ext = "js";
133
- }
134
- const filename = `${(0, _utils.replacePlaceholders)(this.path, {
135
- locale
136
- })}.${ext}`;
137
- await (0, _utils.writeFile)(filename, compiledCatalog);
138
- return filename;
139
- }
140
- async read(locale) {
141
- const filename = (0, _utils.replacePlaceholders)(this.path, {
142
- locale
143
- }) + this.format.getCatalogExtension();
144
- return await this.format.read(filename, locale);
145
- }
146
- async readAll() {
147
- const res = {};
148
- await Promise.all(this.locales.map(async locale => res[locale] = await this.read(locale)));
149
-
150
- // statement above will save locales in object in undetermined order
151
- // resort here to have keys order the same as in locales definition
152
- return this.locales.reduce((acc, locale) => {
153
- acc[locale] = res[locale];
154
- return acc;
155
- }, {});
156
- }
157
- async readTemplate() {
158
- const filename = this.templateFile;
159
- return await this.format.read(filename, undefined);
160
- }
161
- get sourcePaths() {
162
- const includeGlobs = this.include.map(includePath => {
163
- const isDir = (0, _utils.isDirectory)(includePath);
164
- /**
165
- * glob library results from absolute patterns such as /foo/* are mounted onto the root setting using path.join.
166
- * On windows, this will by default result in /foo/* matching C:\foo\bar.txt.
167
- */
168
- return isDir ? (0, _normalizePath.default)(_path.default.resolve(process.cwd(), includePath === "/" ? "" : includePath, "**/*.*")) : includePath;
169
- });
170
- const patterns = includeGlobs.length > 1 ? `{${includeGlobs.join(",")}}` : includeGlobs[0];
171
- return _glob.default.sync(patterns, {
172
- ignore: this.exclude,
173
- mark: true
174
- });
175
- }
176
- get localeDir() {
177
- const localePatternIndex = this.path.indexOf(LOCALE);
178
- if (localePatternIndex === -1) {
179
- throw Error(`Invalid catalog path: ${LOCALE} variable is missing`);
180
- }
181
- return this.path.substr(0, localePatternIndex);
182
- }
183
- get locales() {
184
- return this.config.locales;
185
- }
186
- }
187
- exports.Catalog = Catalog;
188
- function getTemplatePath(ext, path) {
189
- return path.replace(LOCALE_SUFFIX_RE, "messages" + ext);
190
- }
191
- const cleanObsolete = R.filter(message => !message.obsolete);
192
- exports.cleanObsolete = cleanObsolete;
193
- function order(by) {
194
- return {
195
- messageId: orderByMessageId,
196
- message: orderByMessage,
197
- origin: orderByOrigin
198
- }[by];
199
- }
200
-
201
- /**
202
- * Object keys are in the same order as they were created
203
- * https://stackoverflow.com/a/31102605/1535540
204
- */
205
- function orderByMessageId(messages) {
206
- return Object.keys(messages).sort().reduce((acc, key) => {
207
- ;
208
- acc[key] = messages[key];
209
- return acc;
210
- }, {});
211
- }
212
- function orderByOrigin(messages) {
213
- function getFirstOrigin(messageKey) {
214
- const sortedOrigins = messages[messageKey].origin.sort((a, b) => {
215
- if (a[0] < b[0]) return -1;
216
- if (a[0] > b[0]) return 1;
217
- return 0;
218
- });
219
- return sortedOrigins[0];
220
- }
221
- return Object.keys(messages).sort((a, b) => {
222
- const [aFile, aLineNumber] = getFirstOrigin(a);
223
- const [bFile, bLineNumber] = getFirstOrigin(b);
224
- if (aFile < bFile) return -1;
225
- if (aFile > bFile) return 1;
226
- if (aLineNumber < bLineNumber) return -1;
227
- if (aLineNumber > bLineNumber) return 1;
228
- return 0;
229
- }).reduce((acc, key) => {
230
- ;
231
- acc[key] = messages[key];
232
- return acc;
233
- }, {});
234
- }
235
- function orderByMessage(messages) {
236
- return Object.keys(messages).sort((a, b) => {
237
- const aMsg = messages[a].message || "";
238
- const bMsg = messages[b].message || "";
239
- return aMsg.localeCompare(bMsg);
240
- }).reduce((acc, key) => {
241
- ;
242
- acc[key] = messages[key];
243
- return acc;
244
- }, {});
245
- }
@@ -1,72 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.compile = compile;
7
- exports.createCompiledCatalog = createCompiledCatalog;
8
- var t = _interopRequireWildcard(require("@babel/types"));
9
- var _generator = _interopRequireDefault(require("@babel/generator"));
10
- var _compile = require("@lingui/core/compile");
11
- var _pseudoLocalize = _interopRequireDefault(require("./pseudoLocalize"));
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
14
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
15
- function createCompiledCatalog(locale, messages, options) {
16
- const {
17
- strict = false,
18
- namespace = "cjs",
19
- pseudoLocale,
20
- compilerBabelOptions = {}
21
- } = options;
22
- const shouldPseudolocalize = locale === pseudoLocale;
23
- const compiledMessages = Object.keys(messages).reduce((obj, key) => {
24
- // Don't use `key` as a fallback translation in strict mode.
25
- const translation = messages[key] || (!strict ? key : "");
26
- obj[key] = compile(translation, shouldPseudolocalize);
27
- return obj;
28
- }, {});
29
- if (namespace === "json") {
30
- return JSON.stringify({
31
- messages: compiledMessages
32
- });
33
- }
34
- const ast = buildExportStatement(
35
- //build JSON.parse(<compiledMessages>) statement
36
- t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [t.stringLiteral(JSON.stringify(compiledMessages))]), namespace);
37
- const code = (0, _generator.default)(ast, {
38
- minified: true,
39
- jsescOption: {
40
- minimal: true
41
- },
42
- ...compilerBabelOptions
43
- }).code;
44
- return "/*eslint-disable*/" + code;
45
- }
46
- function buildExportStatement(expression, namespace) {
47
- if (namespace === "es" || namespace === "ts") {
48
- // export const messages = { message: "Translation" }
49
- return t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("messages"), expression)]));
50
- } else {
51
- let exportExpression = null;
52
- const matches = namespace.match(/^(window|global)\.([^.\s]+)$/);
53
- if (namespace === "cjs") {
54
- // module.exports.messages = { message: "Translation" }
55
- exportExpression = t.memberExpression(t.identifier("module"), t.identifier("exports"));
56
- } else if (matches) {
57
- // window.i18nMessages = { messages: { message: "Translation" }}
58
- exportExpression = t.memberExpression(t.identifier(matches[1]), t.identifier(matches[2]));
59
- } else {
60
- throw new Error(`Invalid namespace param: "${namespace}"`);
61
- }
62
- return t.expressionStatement(t.assignmentExpression("=", exportExpression, t.objectExpression([t.objectProperty(t.identifier("messages"), expression)])));
63
- }
64
- }
65
-
66
- /**
67
- * Compile string message into AST tree. Message format is parsed/compiled into
68
- * JS arrays, which are handled in client.
69
- */
70
- function compile(message, shouldPseudolocalize = false) {
71
- return (0, _compile.compileMessage)(message, value => shouldPseudolocalize ? (0, _pseudoLocalize.default)(value) : value);
72
- }
@@ -1,92 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _core = require("@babel/core");
8
- var _babelPluginExtractMessages = _interopRequireDefault(require("@lingui/babel-plugin-extract-messages"));
9
- var _sourceMap = require("source-map");
10
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
12
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
- const babelRe = new RegExp("\\.(" + [..._core.DEFAULT_EXTENSIONS, ".ts", ".mts", ".cts", ".tsx"].map(ext => ext.slice(1)).join("|") + ")$", "i");
14
- const inlineSourceMapsRE = new RegExp(/\/[\/\*][#@]\s+sourceMappingURL=data:application\/json;(?:charset:utf-8;)?base64,/i);
15
- const extractor = {
16
- match(filename) {
17
- return babelRe.test(filename);
18
- },
19
- async extract(filename, code, onMessageExtracted, ctx) {
20
- const parserOptions = ctx.linguiConfig.extractorParserOptions;
21
-
22
- // https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
23
- const parserPlugins = [];
24
- if ([/\.ts$/, /\.mts$/, /\.cts$/, /\.tsx$/].some(r => filename.match(r))) {
25
- parserPlugins.push("typescript");
26
- if (parserOptions.tsExperimentalDecorators) {
27
- parserPlugins.push("decorators-legacy");
28
- } else {
29
- parserPlugins.push("decorators");
30
- }
31
- } else {
32
- parserPlugins.push("decorators");
33
- if (parserOptions !== null && parserOptions !== void 0 && parserOptions.flow) {
34
- parserPlugins.push("flow");
35
- }
36
- }
37
- if ([/\.jsx$/, /\.tsx$/].some(r => filename.match(r))) {
38
- parserPlugins.push("jsx");
39
- }
40
- let sourceMapsConsumer;
41
- if (ctx !== null && ctx !== void 0 && ctx.sourceMaps) {
42
- sourceMapsConsumer = await new _sourceMap.SourceMapConsumer(ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps);
43
- } else if (code.search(inlineSourceMapsRE) != -1) {
44
- const {
45
- fromSource
46
- } = await Promise.resolve().then(() => _interopRequireWildcard(require("convert-source-map")));
47
- sourceMapsConsumer = await new _sourceMap.SourceMapConsumer(fromSource(code).toObject());
48
- }
49
- await (0, _core.transformAsync)(code, {
50
- // don't generate code
51
- code: false,
52
- babelrc: false,
53
- configFile: false,
54
- filename: filename,
55
- inputSourceMap: ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps,
56
- parserOpts: {
57
- plugins: parserPlugins
58
- },
59
- plugins: [["macros", {
60
- // macro plugin uses package `resolve` to find a path of macro file
61
- // this will not follow jest pathMapping and will resolve path from ./build
62
- // instead of ./src which makes testing & developing hard.
63
- // here we override resolve and provide correct path for testing
64
- resolvePath: source => require.resolve(source),
65
- lingui: {
66
- extract: true,
67
- linguiConfig: ctx.linguiConfig
68
- }
69
- }], [_babelPluginExtractMessages.default, {
70
- onMessageExtracted: msg => {
71
- if (!sourceMapsConsumer) {
72
- return onMessageExtracted(msg);
73
- }
74
- const [_, line, column] = msg.origin;
75
- const mappedPosition = sourceMapsConsumer.originalPositionFor({
76
- line,
77
- column
78
- });
79
- return onMessageExtracted({
80
- ...msg,
81
- origin: [mappedPosition.source, mappedPosition.line, mappedPosition.column]
82
- });
83
- }
84
- }]]
85
- });
86
- if (sourceMapsConsumer) {
87
- sourceMapsConsumer.destroy();
88
- }
89
- }
90
- };
91
- var _default = extractor;
92
- exports.default = _default;
@@ -1,36 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = extract;
7
- var _promises = _interopRequireDefault(require("fs/promises"));
8
- var _babel = _interopRequireDefault(require("./babel"));
9
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
- const DEFAULT_EXTRACTORS = [_babel.default];
11
- async function extract(filename, onMessageExtracted, linguiConfig, options) {
12
- const extractorsToExtract = options.extractors ?? DEFAULT_EXTRACTORS;
13
- for (let e of extractorsToExtract) {
14
- let ext = e;
15
- if (typeof e === "string") {
16
- // in case of the user using require.resolve in their extractors, we require that module
17
- ext = require(e);
18
- }
19
- if (ext.default) {
20
- ext = ext.default;
21
- }
22
- if (!ext.match(filename)) continue;
23
- try {
24
- const file = await _promises.default.readFile(filename);
25
- await ext.extract(filename, file.toString(), onMessageExtracted, {
26
- linguiConfig
27
- });
28
- return true;
29
- } catch (e) {
30
- console.error(`Cannot process file ${filename} ${e.message}`);
31
- console.error(e.stack);
32
- return false;
33
- }
34
- }
35
- return true;
36
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- const extractor = {
8
- match(filename) {
9
- throw new Error("Typescript extractor was removed. " + "Lingui CLI can parse typescript out of the box. " + "Please remove it from your lingui.config.js");
10
- },
11
- extract() {}
12
- };
13
- var _default = extractor;
14
- exports.default = _default;
@@ -1,45 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.FormatterWrapper = void 0;
7
- var _utils = require("../utils");
8
- var _rethrownError = require("../rethrownError");
9
- class FormatterWrapper {
10
- constructor(f, sourceLocale) {
11
- this.f = f;
12
- this.sourceLocale = sourceLocale;
13
- }
14
- getCatalogExtension() {
15
- return this.f.catalogExtension;
16
- }
17
- getTemplateExtension() {
18
- return this.f.templateExtension || this.f.catalogExtension;
19
- }
20
- async write(filename, catalog, locale) {
21
- const content = await this.f.serialize(catalog, {
22
- locale,
23
- sourceLocale: this.sourceLocale,
24
- existing: await (0, _utils.readFile)(filename),
25
- filename
26
- });
27
- await (0, _utils.writeFileIfChanged)(filename, content);
28
- }
29
- async read(filename, locale) {
30
- const content = await (0, _utils.readFile)(filename);
31
- if (!content) {
32
- return null;
33
- }
34
- try {
35
- return this.f.parse(content, {
36
- locale,
37
- sourceLocale: this.sourceLocale,
38
- filename
39
- });
40
- } catch (e) {
41
- throw new _rethrownError.RethrownError(`Cannot read ${filename}`, e);
42
- }
43
- }
44
- }
45
- exports.FormatterWrapper = FormatterWrapper;