@lingui/cli 4.0.0-next.1 → 4.0.0-next.2

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.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.default = void 0;
6
+ exports.default = _default;
7
7
  exports.deserialize = deserialize;
8
8
  exports.serialize = void 0;
9
9
  var _dateFns = require("date-fns");
@@ -14,14 +14,16 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
14
14
  function isGeneratedId(id, message) {
15
15
  return id === (0, _generateMessageId.generateMessageId)(message.message, message.context);
16
16
  }
17
- function getCreateHeaders(language = "no") {
17
+ function getCreateHeaders(language) {
18
18
  return {
19
19
  "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),
20
20
  "MIME-Version": "1.0",
21
21
  "Content-Type": "text/plain; charset=utf-8",
22
22
  "Content-Transfer-Encoding": "8bit",
23
23
  "X-Generator": "@lingui/cli",
24
- Language: language
24
+ ...(language ? {
25
+ Language: language
26
+ } : {})
25
27
  };
26
28
  }
27
29
  const EXPLICIT_ID_FLAG = "explicit-id";
@@ -92,38 +94,32 @@ function validateItem(item) {
92
94
  console.warn(`Multiple translations for item with key ${item.msgid} is not supported and it will be ignored.`);
93
95
  }
94
96
  }
95
- const po = {
96
- catalogExtension: ".po",
97
- templateExtension: ".pot",
98
- write(filename, catalog, options) {
99
- let po;
100
- const raw = (0, _utils.readFile)(filename);
101
- if (raw) {
102
- po = _pofile.default.parse(raw);
103
- } else {
104
- po = new _pofile.default();
105
- po.headers = getCreateHeaders(options.locale);
106
- if (options.locale === undefined) {
107
- delete po.headers.Language;
97
+ function _default(options = {}) {
98
+ options = {
99
+ origins: true,
100
+ lineNumbers: true,
101
+ ...options
102
+ };
103
+ return {
104
+ catalogExtension: ".po",
105
+ templateExtension: ".pot",
106
+ parse(content) {
107
+ const po = _pofile.default.parse(content);
108
+ return deserialize(po.items, validateItem);
109
+ },
110
+ serialize(catalog, ctx) {
111
+ let po;
112
+ if (ctx.existing) {
113
+ po = _pofile.default.parse(ctx.existing);
114
+ } else {
115
+ po = new _pofile.default();
116
+ po.headers = getCreateHeaders(ctx.locale)
117
+ // accessing private property
118
+ ;
119
+ po.headerOrder = Object.keys(po.headers);
108
120
  }
109
- // accessing private property
110
- ;
111
- po.headerOrder = Object.keys(po.headers);
121
+ po.items = serialize(catalog, options);
122
+ return po.toString();
112
123
  }
113
- po.items = serialize(catalog, options);
114
- (0, _utils.writeFileIfChanged)(filename, po.toString());
115
- },
116
- read(filename) {
117
- const raw = (0, _utils.readFile)(filename);
118
- if (!raw) {
119
- return null;
120
- }
121
- return this.parse(raw);
122
- },
123
- parse(raw) {
124
- const po = _pofile.default.parse(raw);
125
- return deserialize(po.items, validateItem);
126
- }
127
- };
128
- var _default = po;
129
- exports.default = _default;
124
+ };
125
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.RethrownError = void 0;
7
+ class RethrownError extends Error {
8
+ constructor(message, originalError) {
9
+ super();
10
+ this.message = message + " " + originalError.message;
11
+ this.stack = `Error: ${message} \nOriginal: ` + originalError.stack;
12
+ }
13
+ }
14
+ exports.RethrownError = RethrownError;
@@ -31,7 +31,7 @@ function prettyOrigin(origins) {
31
31
  }
32
32
  function replacePlaceholders(input, values) {
33
33
  return input.replace(/\{([^}]+)}/g, (m, placeholder) => {
34
- return values[placeholder] || m;
34
+ return values[placeholder] ?? m;
35
35
  });
36
36
  }
37
37
  const splitOrigin = origin => {
@@ -41,18 +41,18 @@ const splitOrigin = origin => {
41
41
  exports.splitOrigin = splitOrigin;
42
42
  const joinOrigin = origin => origin.join(":");
43
43
  exports.joinOrigin = joinOrigin;
44
- function readFile(fileName) {
44
+ async function readFile(fileName) {
45
45
  try {
46
- return _fs.default.readFileSync(fileName).toString();
46
+ return (await _fs.default.promises.readFile(fileName)).toString();
47
47
  } catch (err) {
48
48
  if (err.code != "ENOENT") {
49
49
  throw err;
50
50
  }
51
51
  }
52
52
  }
53
- function mkdirp(dir) {
53
+ async function mkdirp(dir) {
54
54
  try {
55
- _fs.default.mkdirSync(dir, {
55
+ await _fs.default.promises.mkdir(dir, {
56
56
  recursive: true
57
57
  });
58
58
  } catch (err) {
@@ -70,18 +70,18 @@ function isDirectory(filePath) {
70
70
  }
71
71
  }
72
72
  }
73
- function writeFile(fileName, content) {
74
- mkdirp(_path.default.dirname(fileName));
75
- _fs.default.writeFileSync(fileName, content);
73
+ async function writeFile(fileName, content) {
74
+ await mkdirp(_path.default.dirname(fileName));
75
+ await _fs.default.promises.writeFile(fileName, content);
76
76
  }
77
- function writeFileIfChanged(filename, newContent) {
78
- const raw = readFile(filename);
77
+ async function writeFileIfChanged(filename, newContent) {
78
+ const raw = await readFile(filename);
79
79
  if (raw) {
80
80
  if (newContent !== raw) {
81
- writeFile(filename, newContent);
81
+ await writeFile(filename, newContent);
82
82
  }
83
83
  } else {
84
- writeFile(filename, newContent);
84
+ await writeFile(filename, newContent);
85
85
  }
86
86
  }
87
87
  function hasYarn() {
@@ -110,6 +110,8 @@ function normalizeRelativePath(sourcePath) {
110
110
  // absolute path
111
111
  return (0, _normalizePath.default)(sourcePath, false);
112
112
  }
113
+
114
+ // https://github.com/lingui/js-lingui/issues/809
113
115
  const isDir = isDirectory(sourcePath);
114
116
  return (0, _normalizePath.default)(_path.default.relative(process.cwd(), sourcePath), false) + (isDir ? "/" : "");
115
117
  }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.buildExternalizeFilter = buildExternalizeFilter;
7
+ exports.getPackageJson = getPackageJson;
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 createPackageRegExp(packageName) {
11
+ return new RegExp("^" + packageName + "(?:\\/.+)?");
12
+ }
13
+ function packages(packages, includeDeps) {
14
+ return Object.keys(packages || {}).filter(packageName => {
15
+ return !includeDeps.some(incl => packageName.startsWith(incl));
16
+ }).map(createPackageRegExp);
17
+ }
18
+ function buildExternalizeFilter({
19
+ includeDeps,
20
+ excludeDeps,
21
+ packageJson
22
+ }) {
23
+ const external = [...packages(packageJson.dependencies, includeDeps), ...packages(packageJson.devDependencies, includeDeps), ...packages(packageJson.peerDependencies, includeDeps), ...packages(packageJson.optionalDependencies, includeDeps), ...excludeDeps.map(createPackageRegExp)];
24
+ return id => external.some(regExp => {
25
+ return regExp.test(id);
26
+ });
27
+ }
28
+ async function getPackageJson(rootDir) {
29
+ const {
30
+ default: pkgUp
31
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require("pkg-up")));
32
+ const packageJsonPath = await pkgUp({
33
+ cwd: rootDir
34
+ });
35
+ if (!packageJsonPath) {
36
+ throw new Error("We could not able to find your package.json file. " + "Check that `rootDir` is pointing to the folder with package.json");
37
+ }
38
+ return await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(packageJsonPath);
39
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.bundleSource = bundleSource;
7
+ var _buildExternalizeFilter = require("./buildExternalizeFilter");
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 createExtRegExp(extensions) {
11
+ return new RegExp("\\.(?:" + extensions.join("|") + ")(?:\\?.*)?$");
12
+ }
13
+ async function bundleSource(config, entryPoints, outDir, rootDir) {
14
+ const esbuild = await Promise.resolve().then(() => _interopRequireWildcard(require("esbuild")));
15
+ const excludeExtensions = config.excludeExtensions || ["ico", "pot", "xliff", "woff2", "woff", "eot", "gif", "otf", "ttf", "mp4", "svg", "png", "css", "sass", "less", "jpg"];
16
+ const packageJson = await (0, _buildExternalizeFilter.getPackageJson)(rootDir);
17
+ const esbuildOptions = {
18
+ entryPoints: entryPoints,
19
+ outExtension: {
20
+ ".js": ".jsx"
21
+ },
22
+ jsx: "preserve",
23
+ bundle: true,
24
+ platform: "node",
25
+ target: ["esnext"],
26
+ format: "esm",
27
+ splitting: false,
28
+ treeShaking: true,
29
+ outdir: outDir,
30
+ sourcemap: "inline",
31
+ sourceRoot: outDir,
32
+ sourcesContent: false,
33
+ outbase: rootDir,
34
+ metafile: true,
35
+ plugins: [{
36
+ name: "externalize-deps",
37
+ setup(build) {
38
+ const isExternal = (0, _buildExternalizeFilter.buildExternalizeFilter)({
39
+ includeDeps: config.includeDeps || [],
40
+ excludeDeps: config.excludeDeps || [],
41
+ packageJson
42
+ });
43
+
44
+ // externalize bare imports
45
+ build.onResolve({
46
+ filter: /^[^.].*/
47
+ }, async ({
48
+ path: id
49
+ }) => {
50
+ if (isExternal(id)) {
51
+ return {
52
+ external: true
53
+ };
54
+ }
55
+ });
56
+ }
57
+ }, {
58
+ name: "externalize-files",
59
+ setup(build) {
60
+ build.onResolve({
61
+ filter: createExtRegExp(excludeExtensions)
62
+ }, () => ({
63
+ external: true
64
+ }));
65
+ }
66
+ }]
67
+ };
68
+ return await esbuild.build(config.resolveEsbuildOptions ? config.resolveEsbuildOptions(esbuildOptions) : esbuildOptions);
69
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ENTRY_NAME_PH = exports.DEFAULT_TEMPLATE_NAME = void 0;
7
+ const ENTRY_NAME_PH = "{entryName}";
8
+ exports.ENTRY_NAME_PH = ENTRY_NAME_PH;
9
+ const DEFAULT_TEMPLATE_NAME = "messages";
10
+ exports.DEFAULT_TEMPLATE_NAME = DEFAULT_TEMPLATE_NAME;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getEntryPoints = getEntryPoints;
7
+ var _glob = _interopRequireDefault(require("glob"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ function getEntryPoints(entries) {
10
+ const patterns = entries.length > 1 ? `{${entries.join(",")}}` : entries[0];
11
+ return _glob.default.sync(patterns, {
12
+ mark: true
13
+ });
14
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getExperimentalCatalogs = getExperimentalCatalogs;
7
+ var _getEntryPoints = require("./getEntryPoints");
8
+ var _resolveCatalogPath = require("./resolveCatalogPath");
9
+ var _catalog = require("../api/catalog");
10
+ var _resolveTemplatePath = require("./resolveTemplatePath");
11
+ var _api = require("@lingui/cli/api");
12
+ function getExperimentalCatalogs(linguiConfig) {
13
+ const config = linguiConfig.experimental.extractor;
14
+ const entryPoints = (0, _getEntryPoints.getEntryPoints)(config.entries);
15
+ return entryPoints.map(entryPoint => {
16
+ const catalogPath = (0, _resolveCatalogPath.resolveCatalogPath)(config.output, entryPoint, linguiConfig.rootDir, undefined, "");
17
+ const format = (0, _api.getFormat)(linguiConfig.format, linguiConfig.formatOptions);
18
+ const templatePath = (0, _resolveTemplatePath.resolveTemplatePath)(entryPoint, config.output, linguiConfig.rootDir, format.getTemplateExtension());
19
+ return new _catalog.Catalog({
20
+ name: undefined,
21
+ path: catalogPath,
22
+ templatePath,
23
+ include: [],
24
+ exclude: []
25
+ }, linguiConfig);
26
+ });
27
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getEntryName = getEntryName;
7
+ exports.resolveCatalogPath = resolveCatalogPath;
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _utils = require("../api/utils");
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ function resolveCatalogPath(configOutput, entryPath, rootDir, locale, extension) {
12
+ const entryName = getEntryName(entryPath);
13
+ const entryDir = _path.default.relative(rootDir, _path.default.dirname(entryPath));
14
+ return _path.default.normalize((0, _utils.replacePlaceholders)(configOutput, {
15
+ entryName,
16
+ entryDir,
17
+ locale
18
+ }) + extension);
19
+ }
20
+ function getEntryName(entryPath) {
21
+ const parsedPath = _path.default.parse(entryPath);
22
+ return parsedPath.name.replace(parsedPath.ext, "");
23
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.resolveTemplatePath = resolveTemplatePath;
7
+ var _resolveCatalogPath = require("./resolveCatalogPath");
8
+ var _constants = require("./constants");
9
+ function resolveTemplatePath(entryPoint, output, rootDir, catalogExtension) {
10
+ let templateName;
11
+ if (output.includes(_constants.ENTRY_NAME_PH)) {
12
+ templateName = _constants.DEFAULT_TEMPLATE_NAME;
13
+ } else {
14
+ templateName = (0, _resolveCatalogPath.getEntryName)(entryPoint);
15
+ }
16
+ return (0, _resolveCatalogPath.resolveCatalogPath)(output, entryPoint, rootDir, templateName, catalogExtension);
17
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.writeCatalogs = writeCatalogs;
7
+ exports.writeTemplate = writeTemplate;
8
+ var _resolveTemplatePath = require("./resolveTemplatePath");
9
+ var _chalk = _interopRequireDefault(require("chalk"));
10
+ var _resolveCatalogPath = require("./resolveCatalogPath");
11
+ var _mergeCatalog = require("../api/catalog/mergeCatalog");
12
+ var _stats = require("../api/stats");
13
+ var _catalog = require("../api/catalog");
14
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+ function cleanAndSort(catalog, clean, orderBy) {
16
+ if (clean) {
17
+ catalog = (0, _catalog.cleanObsolete)(catalog);
18
+ }
19
+ return (0, _catalog.order)(orderBy)(catalog);
20
+ }
21
+ async function writeCatalogs(params) {
22
+ const {
23
+ entryPoint,
24
+ outputPattern,
25
+ linguiConfig,
26
+ locales,
27
+ overwrite,
28
+ format,
29
+ clean,
30
+ messages
31
+ } = params;
32
+ const stat = {};
33
+ for (const locale of locales) {
34
+ const catalogOutput = (0, _resolveCatalogPath.resolveCatalogPath)(outputPattern, entryPoint, linguiConfig.rootDir, locale, format.getCatalogExtension());
35
+ const catalog = (0, _mergeCatalog.mergeCatalog)(await format.read(catalogOutput, locale), messages, locale === linguiConfig.sourceLocale, {
36
+ overwrite
37
+ });
38
+ await format.write(catalogOutput, cleanAndSort(catalog, clean, linguiConfig.orderBy), locale);
39
+ stat[locale] = catalog;
40
+ }
41
+ return {
42
+ statMessage: (0, _stats.printStats)(linguiConfig, stat).toString()
43
+ };
44
+ }
45
+ async function writeTemplate(params) {
46
+ const {
47
+ entryPoint,
48
+ outputPattern,
49
+ linguiConfig,
50
+ format,
51
+ clean,
52
+ messages
53
+ } = params;
54
+ const catalogOutput = (0, _resolveTemplatePath.resolveTemplatePath)(entryPoint, outputPattern, linguiConfig.rootDir, format.getTemplateExtension());
55
+ await format.write(catalogOutput, cleanAndSort(messages, clean, linguiConfig.orderBy), undefined);
56
+ return {
57
+ statMessage: `${_chalk.default.bold(Object.keys(messages).length)} message(s) extracted`
58
+ };
59
+ }
@@ -13,8 +13,10 @@ var _compile = require("./api/compile");
13
13
  var _help = require("./api/help");
14
14
  var _api = require("./api");
15
15
  var _getCatalogs = require("./api/catalog/getCatalogs");
16
+ var _utils = require("./api/utils");
17
+ var _path = _interopRequireDefault(require("path"));
16
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
- function command(config, options) {
19
+ async function command(config, options) {
18
20
  const catalogs = (0, _api.getCatalogs)(config);
19
21
 
20
22
  // Check config.compile.merge if catalogs for current locale are to be merged into a single compiled file
@@ -24,7 +26,7 @@ function command(config, options) {
24
26
  for (const locale of config.locales) {
25
27
  for (const catalog of catalogs) {
26
28
  const missingMessages = [];
27
- const messages = catalog.getTranslations(locale, {
29
+ const messages = await catalog.getTranslations(locale, {
28
30
  fallbackLocales: config.fallbackLocales,
29
31
  sourceLocale: config.sourceLocale,
30
32
  onMissing: missing => {
@@ -58,7 +60,7 @@ function command(config, options) {
58
60
  pseudoLocale: config.pseudoLocale,
59
61
  compilerBabelOptions: config.compilerBabelOptions
60
62
  });
61
- const compiledPath = catalog.writeCompiled(locale, compiledCatalog, namespace);
63
+ let compiledPath = await catalog.writeCompiled(locale, compiledCatalog, namespace);
62
64
  if (options.typescript) {
63
65
  const typescriptPath = compiledPath.replace(/\.ts?$/, "") + ".d.ts";
64
66
  _fs.default.writeFileSync(typescriptPath, `import { Messages } from '@lingui/core';
@@ -66,6 +68,7 @@ function command(config, options) {
66
68
  export { messages };
67
69
  `);
68
70
  }
71
+ compiledPath = (0, _utils.normalizeSlashes)(_path.default.relative(config.rootDir, compiledPath));
69
72
  options.verbose && console.error(_chalk.default.green(`${locale} ⇒ ${compiledPath}`));
70
73
  }
71
74
  }
@@ -78,7 +81,8 @@ function command(config, options) {
78
81
  pseudoLocale: config.pseudoLocale,
79
82
  compilerBabelOptions: config.compilerBabelOptions
80
83
  });
81
- const compiledPath = compileCatalog.writeCompiled(locale, compiledCatalog, namespace);
84
+ let compiledPath = await compileCatalog.writeCompiled(locale, compiledCatalog, namespace);
85
+ compiledPath = (0, _utils.normalizeSlashes)(_path.default.relative(config.rootDir, compiledPath));
82
86
  options.verbose && console.log(_chalk.default.green(`${locale} ⇒ ${compiledPath}`));
83
87
  }
84
88
  }
@@ -99,17 +103,21 @@ if (require.main === module) {
99
103
  const config = (0, _conf.getConfig)({
100
104
  configPath: options.config
101
105
  });
102
- const compile = () => command(config, {
103
- verbose: options.watch || options.verbose || false,
104
- allowEmpty: !options.strict,
105
- typescript: options.typescript || config.compileNamespace === "ts" || false,
106
- namespace: options.namespace // we want this to be undefined if user does not specify so default can be used
107
- });
106
+ let previousRun = Promise.resolve(true);
107
+ const compile = () => {
108
+ previousRun = previousRun.then(() => command(config, {
109
+ verbose: options.watch || options.verbose || false,
110
+ allowEmpty: !options.strict,
111
+ typescript: options.typescript || config.compileNamespace === "ts" || false,
112
+ namespace: options.namespace // we want this to be undefined if user does not specify so default can be used
113
+ }));
108
114
 
115
+ return previousRun;
116
+ };
109
117
  let debounceTimer;
110
118
  const dispatchCompile = () => {
111
119
  // Skip debouncing if not enabled
112
- if (!options.debounce) return compile();
120
+ if (!options.debounce) compile();
113
121
 
114
122
  // CLear the previous timer if there is any, and schedule the next
115
123
  debounceTimer && clearTimeout(debounceTimer);
@@ -121,7 +129,7 @@ if (require.main === module) {
121
129
  console.info(_chalk.default.bold("Initializing Watch Mode..."));
122
130
  const catalogs = (0, _api.getCatalogs)(config);
123
131
  let paths = [];
124
- const catalogExtension = (0, _api.getFormat)(config.format).catalogExtension;
132
+ const catalogExtension = (0, _api.getFormat)(config.format, config.formatOptions).getCatalogExtension();
125
133
  config.locales.forEach(locale => {
126
134
  catalogs.forEach(catalog => {
127
135
  paths.push(`${catalog.path.replace(/{locale}/g, locale).replace(/{name}/g, "*")}${catalogExtension}`);
@@ -136,10 +144,11 @@ if (require.main === module) {
136
144
  };
137
145
  watcher.on("ready", () => onReady());
138
146
  } else {
139
- const results = compile();
140
- if (!results) {
141
- process.exit(1);
142
- }
143
- console.log("Done!");
147
+ compile().then(results => {
148
+ if (!results) {
149
+ process.exit(1);
150
+ }
151
+ console.log("Done!");
152
+ });
144
153
  }
145
154
  }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = command;
7
+ var _commander = require("commander");
8
+ var _conf = require("@lingui/conf");
9
+ var _path = _interopRequireDefault(require("path"));
10
+ var _os = _interopRequireDefault(require("os"));
11
+ var _formats = require("./api/formats");
12
+ var _promises = _interopRequireDefault(require("fs/promises"));
13
+ var _extractFromFiles = require("./api/catalog/extractFromFiles");
14
+ var _utils = require("./api/utils");
15
+ var _bundleSource = require("./extract-experimental/bundleSource");
16
+ var _writeCatalogs = require("./extract-experimental/writeCatalogs");
17
+ var _getEntryPoints = require("./extract-experimental/getEntryPoints");
18
+ var _chalk = _interopRequireDefault(require("chalk"));
19
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20
+ async function command(linguiConfig, options) {
21
+ var _linguiConfig$experim;
22
+ options.verbose && console.log("Extracting messages from source files…");
23
+ const config = (_linguiConfig$experim = linguiConfig.experimental) === null || _linguiConfig$experim === void 0 ? void 0 : _linguiConfig$experim.extractor;
24
+ if (!config) {
25
+ throw new Error("The configuration for experimental extractor is empty. Please read the docs.");
26
+ }
27
+ console.log(_chalk.default.yellow(["You have using an experimental feature", "Experimental features are not covered by semver, and may cause unexpected or broken application behavior." + " Use at your own risk.", ""].join("\n")));
28
+ const tempDir = await _promises.default.mkdtemp(_path.default.join(_os.default.tmpdir(), "js-lingui-extract-"));
29
+ await _promises.default.rm(tempDir, {
30
+ recursive: true,
31
+ force: true
32
+ });
33
+ const bundleResult = await (0, _bundleSource.bundleSource)(config, (0, _getEntryPoints.getEntryPoints)(config.entries), tempDir, linguiConfig.rootDir);
34
+ const stats = [];
35
+ let commandSuccess = true;
36
+ const format = (0, _formats.getFormat)(linguiConfig.format, linguiConfig.formatOptions);
37
+ for (const outFile of Object.keys(bundleResult.metafile.outputs)) {
38
+ const messages = await (0, _extractFromFiles.extractFromFiles)([outFile], linguiConfig);
39
+ const {
40
+ entryPoint
41
+ } = bundleResult.metafile.outputs[outFile];
42
+ let output;
43
+ if (!messages) {
44
+ commandSuccess = false;
45
+ continue;
46
+ }
47
+ if (options.template) {
48
+ output = (await (0, _writeCatalogs.writeTemplate)({
49
+ linguiConfig,
50
+ clean: options.clean,
51
+ format,
52
+ messages,
53
+ entryPoint,
54
+ outputPattern: config.output
55
+ })).statMessage;
56
+ } else {
57
+ output = (await (0, _writeCatalogs.writeCatalogs)({
58
+ locales: options.locales || linguiConfig.locales,
59
+ linguiConfig,
60
+ clean: options.clean,
61
+ format,
62
+ messages,
63
+ entryPoint,
64
+ overwrite: options.overwrite,
65
+ outputPattern: config.output
66
+ })).statMessage;
67
+ }
68
+ stats.push({
69
+ entry: (0, _utils.normalizeSlashes)(_path.default.relative(linguiConfig.rootDir, entryPoint)),
70
+ content: output
71
+ });
72
+ }
73
+
74
+ // cleanup temp directory
75
+ await _promises.default.rm(tempDir, {
76
+ recursive: true,
77
+ force: true
78
+ });
79
+ stats.forEach(({
80
+ entry,
81
+ content
82
+ }) => {
83
+ console.log([`Catalog statistics for ${entry}:`, content, ""].join("\n"));
84
+ });
85
+ return commandSuccess;
86
+ }
87
+ if (require.main === module) {
88
+ var _options$locale;
89
+ _commander.program.option("--config <path>", "Path to the config file").option("--template", "Extract to template").option("--overwrite", "Overwrite translations for source locale").option("--clean", "Remove obsolete translations").option("--locale <locale, [...]>", "Only extract the specified locales").option("--verbose", "Verbose output").parse(process.argv);
90
+ const options = _commander.program.opts();
91
+ const config = (0, _conf.getConfig)({
92
+ configPath: options.config
93
+ });
94
+ const result = command(config, {
95
+ verbose: options.verbose || false,
96
+ template: options.template,
97
+ locales: (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : _options$locale.split(","),
98
+ overwrite: options.overwrite,
99
+ clean: options.clean
100
+ }).then(() => {
101
+ if (!result) process.exit(1);
102
+ });
103
+ }
@@ -49,7 +49,7 @@ async function command(config, options) {
49
49
  // If service key is present in configuration, synchronize with cloud translation platform
50
50
  if (typeof config.service === "object" && config.service.name && config.service.name.length) {
51
51
  const moduleName = config.service.name.charAt(0).toLowerCase() + config.service.name.slice(1);
52
- (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`./services/${moduleName}`).then(module => module.default(config, options)).catch(err => console.error(`Can't load service module ${moduleName}`, err));
52
+ await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`./services/${moduleName}`).then(module => module.default(config, options)).catch(err => console.error(`Can't load service module ${moduleName}`, err));
53
53
  }
54
54
  return commandSuccess;
55
55
  }
package/build/lingui.js CHANGED
@@ -3,4 +3,4 @@
3
3
 
4
4
  var _commander = require("commander");
5
5
  var _package = require("../package.json");
6
- _commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);
6
+ _commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-experimental", "Extracts messages from source files traversing dependency tree").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);