@lingui/cli 4.11.4 → 5.0.0-next.1

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.
@@ -8,6 +8,18 @@ const chalk_1 = __importDefault(require("chalk"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const extractors_1 = __importDefault(require("../extractors"));
10
10
  const utils_1 = require("../utils");
11
+ function mergePlaceholders(prev, next) {
12
+ const res = Object.assign({}, prev);
13
+ Object.entries(next).forEach(([key, value]) => {
14
+ if (!res[key]) {
15
+ res[key] = [];
16
+ }
17
+ if (!res[key].includes(value)) {
18
+ res[key].push(value);
19
+ }
20
+ });
21
+ return res;
22
+ }
11
23
  async function extractFromFiles(paths, config) {
12
24
  const messages = {};
13
25
  let catalogSuccess = true;
@@ -18,6 +30,7 @@ async function extractFromFiles(paths, config) {
18
30
  messages[next.id] = {
19
31
  message: next.message,
20
32
  context: next.context,
33
+ placeholders: {},
21
34
  comments: [],
22
35
  origin: [],
23
36
  };
@@ -35,7 +48,7 @@ async function extractFromFiles(paths, config) {
35
48
  }
36
49
  messages[next.id] = Object.assign(Object.assign({}, prev), { message: (_a = prev.message) !== null && _a !== void 0 ? _a : next.message, comments: next.comment
37
50
  ? [...prev.comments, next.comment]
38
- : prev.comments, origin: [...prev.origin, [filename, next.origin[1]]] });
51
+ : prev.comments, origin: [...prev.origin, [filename, next.origin[1]]], placeholders: mergePlaceholders(prev.placeholders, next.placeholders) });
39
52
  }, config, {
40
53
  extractors: config.extractors,
41
54
  });
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getCatalogForFile = exports.getCatalogForMerge = exports.getCatalogs = void 0;
7
- const glob_1 = __importDefault(require("glob"));
7
+ const glob_1 = require("glob");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const catalog_1 = require("../catalog");
10
10
  const utils_1 = require("../utils");
@@ -45,7 +45,7 @@ async function getCatalogs(config) {
45
45
  return;
46
46
  }
47
47
  const patterns = include.map((path) => (0, utils_1.replacePlaceholders)(path, { name: "*" }));
48
- const candidates = glob_1.default.sync(patterns.length > 1 ? `{${patterns.join(",")}}` : patterns[0], {
48
+ const candidates = (0, glob_1.globSync)(patterns, {
49
49
  ignore: exclude,
50
50
  mark: true,
51
51
  });
@@ -30,7 +30,7 @@ exports.orderByMessage = exports.order = exports.cleanObsolete = exports.Catalog
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const path_1 = __importDefault(require("path"));
32
32
  const R = __importStar(require("ramda"));
33
- const glob_1 = __importDefault(require("glob"));
33
+ const glob_1 = require("glob");
34
34
  const normalize_path_1 = __importDefault(require("normalize-path"));
35
35
  const getTranslationsForCatalog_1 = require("./catalog/getTranslationsForCatalog");
36
36
  const mergeCatalog_1 = require("./catalog/mergeCatalog");
@@ -70,7 +70,7 @@ class Catalog {
70
70
  // Sort messages
71
71
  order(options.orderBy)));
72
72
  const sortedCatalogs = cleanAndSort(catalogs);
73
- const locales = options.locale ? [options.locale] : this.locales;
73
+ const locales = options.locale ? options.locale : this.locales;
74
74
  await Promise.all(locales.map((locale) => this.write(locale, sortedCatalogs[locale])));
75
75
  return sortedCatalogs;
76
76
  }
@@ -90,7 +90,7 @@ class Catalog {
90
90
  if (options.files) {
91
91
  options.files = options.files.map((p) => (0, utils_1.makePathRegexSafe)((0, normalize_path_1.default)(p, false)));
92
92
  const regex = new RegExp(options.files.join("|"), "i");
93
- paths = paths.filter((path) => regex.test(path));
93
+ paths = paths.filter((path) => regex.test((0, normalize_path_1.default)(path)));
94
94
  }
95
95
  return await (0, extractFromFiles_1.extractFromFiles)(paths, this.config);
96
96
  }
@@ -177,15 +177,14 @@ class Catalog {
177
177
  ? (0, normalize_path_1.default)(path_1.default.resolve(process.cwd(), includePath === "/" ? "" : includePath, "**/*.*"))
178
178
  : includePath;
179
179
  });
180
- const patterns = includeGlobs.length > 1 ? `{${includeGlobs.join(",")}}` : includeGlobs[0];
181
- return glob_1.default.sync(patterns, { ignore: this.exclude, mark: true });
180
+ return (0, glob_1.globSync)(includeGlobs, { ignore: this.exclude, mark: true });
182
181
  }
183
182
  get localeDir() {
184
183
  const localePatternIndex = this.path.indexOf(LOCALE);
185
184
  if (localePatternIndex === -1) {
186
185
  throw Error(`Invalid catalog path: ${LOCALE} variable is missing`);
187
186
  }
188
- return this.path.substr(0, localePatternIndex);
187
+ return this.path.substring(0, localePatternIndex);
189
188
  }
190
189
  get locales() {
191
190
  return this.config.locales;
@@ -1,6 +1,6 @@
1
1
  import { ParserOptions } from "@babel/core";
2
- import type { ExtractorType } from "@lingui/conf";
3
- import { ExtractedMessage, ExtractorCtx } from "@lingui/conf";
2
+ import { ExtractorType, LinguiConfig, ExtractedMessage, ExtractorCtx } from "@lingui/conf";
3
+ export declare const babelRe: RegExp;
4
4
  /**
5
5
  * @public
6
6
  *
@@ -26,6 +26,7 @@ import { ExtractedMessage, ExtractorCtx } from "@lingui/conf";
26
26
  * }
27
27
  * ```
28
28
  */
29
- export declare function extractFromFileWithBabel(filename: string, code: string, onMessageExtracted: (msg: ExtractedMessage) => void, ctx: ExtractorCtx, parserOpts: ParserOptions): Promise<void>;
29
+ export declare function extractFromFileWithBabel(filename: string, code: string, onMessageExtracted: (msg: ExtractedMessage) => void, ctx: ExtractorCtx, parserOpts: ParserOptions, skipMacroPlugin?: boolean): Promise<void>;
30
+ export declare function getBabelParserOptions(filename: string, parserOptions: LinguiConfig["extractorParserOptions"]): (import("@babel/parser").ParserPluginWithOptions | ("decimal" | "placeholders" | "asyncDoExpressions" | "asyncGenerators" | "bigInt" | "classPrivateMethods" | "classPrivateProperties" | "classProperties" | "classStaticBlock" | "decorators-legacy" | "decoratorAutoAccessors" | "destructuringPrivate" | "doExpressions" | "dynamicImport" | "explicitResourceManagement" | "exportDefaultFrom" | "exportNamespaceFrom" | "flow" | "flowComments" | "functionBind" | "functionSent" | "importMeta" | "jsx" | "logicalAssignment" | "importAssertions" | "importReflection" | "moduleBlocks" | "moduleStringNames" | "nullishCoalescingOperator" | "numericSeparator" | "objectRestSpread" | "optionalCatchBinding" | "optionalChaining" | "partialApplication" | "privateIn" | "regexpUnicodeSets" | "throwExpressions" | "topLevelAwait" | "v8intrinsic" | "decorators" | "estree" | "moduleAttributes" | "pipelineOperator" | "recordAndTuple" | "typescript"))[];
30
31
  declare const extractor: ExtractorType;
31
32
  export default extractor;
@@ -3,10 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.extractFromFileWithBabel = void 0;
6
+ exports.getBabelParserOptions = exports.extractFromFileWithBabel = exports.babelRe = void 0;
7
7
  const core_1 = require("@babel/core");
8
8
  const babel_plugin_extract_messages_1 = __importDefault(require("@lingui/babel-plugin-extract-messages"));
9
- const babelRe = new RegExp("\\.(" +
9
+ const babel_plugin_lingui_macro_1 = __importDefault(require("@lingui/babel-plugin-lingui-macro"));
10
+ exports.babelRe = new RegExp("\\.(" +
10
11
  [...core_1.DEFAULT_EXTENSIONS, ".ts", ".mts", ".cts", ".tsx"]
11
12
  .map((ext) => ext.slice(1))
12
13
  .join("|") +
@@ -30,7 +31,8 @@ async function createSourceMapper(code, sourceMaps) {
30
31
  else if (code.search(inlineSourceMapsRE) != -1) {
31
32
  const { SourceMapConsumer } = await import("source-map");
32
33
  const { fromSource } = await import("convert-source-map");
33
- sourceMapsConsumer = await new SourceMapConsumer(fromSource(code).toObject());
34
+ const t = fromSource(code).toObject();
35
+ sourceMapsConsumer = await new SourceMapConsumer(t);
34
36
  }
35
37
  return {
36
38
  destroy: () => {
@@ -76,7 +78,7 @@ async function createSourceMapper(code, sourceMaps) {
76
78
  * }
77
79
  * ```
78
80
  */
79
- async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, parserOpts) {
81
+ async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, parserOpts, skipMacroPlugin = false) {
80
82
  const mapper = await createSourceMapper(code, ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps);
81
83
  await (0, core_1.transformAsync)(code, {
82
84
  // don't generate code
@@ -87,20 +89,17 @@ async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx,
87
89
  inputSourceMap: ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps,
88
90
  parserOpts,
89
91
  plugins: [
90
- [
91
- "macros",
92
- {
93
- // macro plugin uses package `resolve` to find a path of macro file
94
- // this will not follow jest pathMapping and will resolve path from ./build
95
- // instead of ./src which makes testing & developing hard.
96
- // here we override resolve and provide correct path for testing
97
- resolvePath: (source) => require.resolve(source),
98
- lingui: {
99
- extract: true,
100
- linguiConfig: ctx.linguiConfig,
101
- },
102
- },
103
- ],
92
+ ...(!skipMacroPlugin
93
+ ? [
94
+ [
95
+ babel_plugin_lingui_macro_1.default,
96
+ {
97
+ extract: true,
98
+ linguiConfig: ctx.linguiConfig,
99
+ },
100
+ ],
101
+ ]
102
+ : []),
104
103
  [
105
104
  babel_plugin_extract_messages_1.default,
106
105
  {
@@ -114,34 +113,38 @@ async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx,
114
113
  mapper.destroy();
115
114
  }
116
115
  exports.extractFromFileWithBabel = extractFromFileWithBabel;
117
- const extractor = {
118
- match(filename) {
119
- return babelRe.test(filename);
120
- },
121
- async extract(filename, code, onMessageExtracted, ctx) {
122
- const parserOptions = ctx.linguiConfig.extractorParserOptions;
123
- // https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
124
- const parserPlugins = [];
125
- if ([/\.ts$/, /\.mts$/, /\.cts$/, /\.tsx$/].some((r) => filename.match(r))) {
126
- parserPlugins.push("typescript");
127
- if (parserOptions.tsExperimentalDecorators) {
128
- parserPlugins.push("decorators-legacy");
129
- }
130
- else {
131
- parserPlugins.push("decorators");
132
- }
116
+ function getBabelParserOptions(filename, parserOptions) {
117
+ // https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
118
+ const parserPlugins = [];
119
+ if ([/\.ts$/, /\.mts$/, /\.cts$/, /\.tsx$/].some((r) => filename.match(r))) {
120
+ parserPlugins.push("typescript");
121
+ if (parserOptions.tsExperimentalDecorators) {
122
+ parserPlugins.push("decorators-legacy");
133
123
  }
134
124
  else {
135
125
  parserPlugins.push("decorators");
136
- if (parserOptions === null || parserOptions === void 0 ? void 0 : parserOptions.flow) {
137
- parserPlugins.push("flow");
138
- }
139
126
  }
140
- if ([/\.js$/, /\.jsx$/, /\.tsx$/].some((r) => filename.match(r))) {
141
- parserPlugins.push("jsx");
127
+ }
128
+ else {
129
+ parserPlugins.push("decorators");
130
+ if (parserOptions === null || parserOptions === void 0 ? void 0 : parserOptions.flow) {
131
+ parserPlugins.push("flow");
142
132
  }
133
+ }
134
+ if ([/\.js$/, /\.jsx$/, /\.tsx$/].some((r) => filename.match(r))) {
135
+ parserPlugins.push("jsx");
136
+ }
137
+ return parserPlugins;
138
+ }
139
+ exports.getBabelParserOptions = getBabelParserOptions;
140
+ const extractor = {
141
+ match(filename) {
142
+ return exports.babelRe.test(filename);
143
+ },
144
+ async extract(filename, code, onMessageExtracted, ctx) {
145
+ const parserOptions = ctx.linguiConfig.extractorParserOptions;
143
146
  return extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, {
144
- plugins: parserPlugins,
147
+ plugins: getBabelParserOptions(filename, parserOptions),
145
148
  });
146
149
  },
147
150
  };
@@ -7,10 +7,6 @@ export declare function writeFile(fileName: string, content: string): Promise<vo
7
7
  export declare function writeFileIfChanged(filename: string, newContent: string): Promise<void>;
8
8
  export declare function hasYarn(): boolean;
9
9
  export declare function makeInstall(packageName: string, dev?: boolean): string;
10
- /**
11
- * Normalize Windows backslashes in path so they look always as posix
12
- */
13
- export declare function normalizeSlashes(path: string): string;
14
10
  /**
15
11
  * Remove ./ at the beginning: ./relative => relative
16
12
  * relative => relative
package/dist/api/utils.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makePathRegexSafe = exports.normalizeRelativePath = exports.normalizeSlashes = exports.makeInstall = exports.hasYarn = exports.writeFileIfChanged = exports.writeFile = exports.isDirectory = exports.readFile = exports.replacePlaceholders = exports.prettyOrigin = exports.PATHSEP = void 0;
6
+ exports.makePathRegexSafe = exports.normalizeRelativePath = exports.makeInstall = exports.hasYarn = exports.writeFileIfChanged = exports.writeFile = exports.isDirectory = exports.readFile = exports.replacePlaceholders = exports.prettyOrigin = exports.PATHSEP = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const normalize_path_1 = __importDefault(require("normalize-path"));
@@ -86,13 +86,6 @@ function makeInstall(packageName, dev = false) {
86
86
  : `npm install ${dev ? "--save-dev" : "--save"} ${packageName}`;
87
87
  }
88
88
  exports.makeInstall = makeInstall;
89
- /**
90
- * Normalize Windows backslashes in path so they look always as posix
91
- */
92
- function normalizeSlashes(path) {
93
- return path.replace("\\", "/");
94
- }
95
- exports.normalizeSlashes = normalizeSlashes;
96
89
  /**
97
90
  * Remove ./ at the beginning: ./relative => relative
98
91
  * relative => relative
@@ -1,2 +1,2 @@
1
- import { ExperimentalExtractorOptions } from "@lingui/conf";
2
- export declare function bundleSource(config: ExperimentalExtractorOptions, entryPoints: string[], outDir: string, rootDir: string): Promise<import("esbuild").BuildResult<any>>;
1
+ import { LinguiConfigNormalized } from "@lingui/conf";
2
+ export declare function bundleSource(linguiConfig: LinguiConfigNormalized, entryPoints: string[], outDir: string, rootDir: string): Promise<import("esbuild").BuildResult<any>>;
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.bundleSource = void 0;
4
- const buildExternalizeFilter_1 = require("./buildExternalizeFilter");
4
+ const linguiEsbuildPlugin_1 = require("./linguiEsbuildPlugin");
5
5
  function createExtRegExp(extensions) {
6
6
  return new RegExp("\\.(?:" + extensions.join("|") + ")(?:\\?.*)?$");
7
7
  }
8
- async function bundleSource(config, entryPoints, outDir, rootDir) {
8
+ async function bundleSource(linguiConfig, entryPoints, outDir, rootDir) {
9
9
  const esbuild = await import("esbuild");
10
+ const config = linguiConfig.experimental.extractor;
10
11
  const excludeExtensions = config.excludeExtensions || [
11
12
  "ico",
12
13
  "pot",
@@ -26,7 +27,6 @@ async function bundleSource(config, entryPoints, outDir, rootDir) {
26
27
  "less",
27
28
  "jpg",
28
29
  ];
29
- const packageJson = await (0, buildExternalizeFilter_1.getPackageJson)(rootDir);
30
30
  const esbuildOptions = {
31
31
  entryPoints: entryPoints,
32
32
  outExtension: { ".js": ".jsx" },
@@ -41,27 +41,10 @@ async function bundleSource(config, entryPoints, outDir, rootDir) {
41
41
  sourcemap: "inline",
42
42
  sourceRoot: outDir,
43
43
  sourcesContent: false,
44
- outbase: rootDir,
44
+ packages: "external",
45
45
  metafile: true,
46
46
  plugins: [
47
- {
48
- name: "externalize-deps",
49
- setup(build) {
50
- const isExternal = (0, buildExternalizeFilter_1.buildExternalizeFilter)({
51
- includeDeps: config.includeDeps || [],
52
- excludeDeps: config.excludeDeps || [],
53
- packageJson,
54
- });
55
- // externalize bare imports
56
- build.onResolve({ filter: /^[^.].*/ }, async ({ path: id }) => {
57
- if (isExternal(id)) {
58
- return {
59
- external: true,
60
- };
61
- }
62
- });
63
- },
64
- },
47
+ (0, linguiEsbuildPlugin_1.pluginLinguiMacro)({ linguiConfig }),
65
48
  {
66
49
  name: "externalize-files",
67
50
  setup(build) {
@@ -1,12 +1,8 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.getEntryPoints = void 0;
7
- const glob_1 = __importDefault(require("glob"));
4
+ const glob_1 = require("glob");
8
5
  function getEntryPoints(entries) {
9
- const patterns = entries.length > 1 ? `{${entries.join(",")}}` : entries[0];
10
- return glob_1.default.sync(patterns, { mark: true });
6
+ return (0, glob_1.globSync)(entries, { mark: true });
11
7
  }
12
8
  exports.getEntryPoints = getEntryPoints;
@@ -0,0 +1,5 @@
1
+ import { Plugin } from "esbuild";
2
+ import { LinguiConfigNormalized } from "@lingui/conf";
3
+ export declare const pluginLinguiMacro: (options: {
4
+ linguiConfig: LinguiConfigNormalized;
5
+ }) => Plugin;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.pluginLinguiMacro = void 0;
7
+ const core_1 = require("@babel/core");
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const babel_1 = require("../api/extractors/babel");
11
+ const babel_plugin_lingui_macro_1 = __importDefault(require("@lingui/babel-plugin-lingui-macro"));
12
+ const pluginLinguiMacro = (options) => ({
13
+ name: "linguiMacro",
14
+ setup(build) {
15
+ build.onLoad({ filter: babel_1.babelRe, namespace: "" }, async (args) => {
16
+ const filename = path_1.default.relative(process.cwd(), args.path);
17
+ const contents = await fs_1.default.promises.readFile(args.path, "utf8");
18
+ const hasMacroRe = /from ["']@lingui(\/.+)?\/macro["']/g;
19
+ if (!hasMacroRe.test(contents)) {
20
+ // let esbuild process file as usual
21
+ return undefined;
22
+ }
23
+ const result = await (0, core_1.transformAsync)(contents, {
24
+ babelrc: false,
25
+ configFile: false,
26
+ filename: filename,
27
+ sourceMaps: "inline",
28
+ parserOpts: {
29
+ plugins: (0, babel_1.getBabelParserOptions)(filename, options.linguiConfig.extractorParserOptions),
30
+ },
31
+ plugins: [
32
+ [
33
+ babel_plugin_lingui_macro_1.default,
34
+ {
35
+ extract: true,
36
+ linguiConfig: options.linguiConfig,
37
+ },
38
+ ],
39
+ ],
40
+ });
41
+ return { contents: result.code, loader: "tsx" };
42
+ });
43
+ },
44
+ });
45
+ exports.pluginLinguiMacro = pluginLinguiMacro;
@@ -12,7 +12,7 @@ const compile_1 = require("./api/compile");
12
12
  const help_1 = require("./api/help");
13
13
  const api_1 = require("./api");
14
14
  const getCatalogs_1 = require("./api/catalog/getCatalogs");
15
- const utils_1 = require("./api/utils");
15
+ const normalize_path_1 = __importDefault(require("normalize-path"));
16
16
  const path_1 = __importDefault(require("path"));
17
17
  async function command(config, options) {
18
18
  const catalogs = await (0, api_1.getCatalogs)(config);
@@ -61,7 +61,7 @@ async function command(config, options) {
61
61
  compilerBabelOptions: config.compilerBabelOptions,
62
62
  });
63
63
  let compiledPath = await catalog.writeCompiled(locale, compiledCatalog, namespace);
64
- compiledPath = (0, utils_1.normalizeSlashes)(path_1.default.relative(config.rootDir, compiledPath));
64
+ compiledPath = (0, normalize_path_1.default)(path_1.default.relative(config.rootDir, compiledPath));
65
65
  options.verbose &&
66
66
  console.error(chalk_1.default.green(`${locale} ⇒ ${compiledPath}`));
67
67
  }
@@ -76,7 +76,7 @@ async function command(config, options) {
76
76
  compilerBabelOptions: config.compilerBabelOptions,
77
77
  });
78
78
  let compiledPath = await compileCatalog.writeCompiled(locale, compiledCatalog, namespace);
79
- compiledPath = (0, utils_1.normalizeSlashes)(path_1.default.relative(config.rootDir, compiledPath));
79
+ compiledPath = (0, normalize_path_1.default)(path_1.default.relative(config.rootDir, compiledPath));
80
80
  options.verbose && console.log(chalk_1.default.green(`${locale} ⇒ ${compiledPath}`));
81
81
  }
82
82
  }
@@ -7,15 +7,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const commander_1 = require("commander");
8
8
  const conf_1 = require("@lingui/conf");
9
9
  const path_1 = __importDefault(require("path"));
10
- const os_1 = __importDefault(require("os"));
11
10
  const formats_1 = require("./api/formats");
12
11
  const promises_1 = __importDefault(require("fs/promises"));
13
12
  const extractFromFiles_1 = require("./api/catalog/extractFromFiles");
14
- const utils_1 = require("./api/utils");
13
+ const normalize_path_1 = __importDefault(require("normalize-path"));
15
14
  const bundleSource_1 = require("./extract-experimental/bundleSource");
16
15
  const writeCatalogs_1 = require("./extract-experimental/writeCatalogs");
17
16
  const getEntryPoints_1 = require("./extract-experimental/getEntryPoints");
18
17
  const chalk_1 = __importDefault(require("chalk"));
18
+ const babel_1 = require("./api/extractors/babel");
19
19
  async function command(linguiConfig, options) {
20
20
  var _a;
21
21
  options.verbose && console.log("Extracting messages from source files…");
@@ -29,12 +29,33 @@ async function command(linguiConfig, options) {
29
29
  " Use at your own risk.",
30
30
  "",
31
31
  ].join("\n")));
32
- const tempDir = await promises_1.default.mkdtemp(path_1.default.join(os_1.default.tmpdir(), "js-lingui-extract-"));
32
+ // unfortunately we can't use os.tmpdir() in this case
33
+ // on windows it might create a folder on a different disk then source code is stored
34
+ // (tmpdir would be always on C: but code could be stored on D:)
35
+ // and then relative path in sourcemaps produced by esbuild will be broken.
36
+ // sourcemaps itself doesn't allow to have absolute windows path, because they are not URL compatible.
37
+ // that's why we store esbuild bundles in .lingui folder
38
+ const tmpPrefix = ".lingui/";
39
+ await promises_1.default.mkdir(tmpPrefix, { recursive: true });
40
+ const tempDir = await promises_1.default.mkdtemp(tmpPrefix);
33
41
  await promises_1.default.rm(tempDir, { recursive: true, force: true });
34
- const bundleResult = await (0, bundleSource_1.bundleSource)(config, (0, getEntryPoints_1.getEntryPoints)(config.entries), tempDir, linguiConfig.rootDir);
42
+ const bundleResult = await (0, bundleSource_1.bundleSource)(linguiConfig, (0, getEntryPoints_1.getEntryPoints)(config.entries), tempDir, linguiConfig.rootDir);
35
43
  const stats = [];
36
44
  let commandSuccess = true;
37
45
  const format = await (0, formats_1.getFormat)(linguiConfig.format, linguiConfig.formatOptions, linguiConfig.sourceLocale);
46
+ linguiConfig.extractors = [
47
+ {
48
+ match(_filename) {
49
+ return true;
50
+ },
51
+ async extract(filename, code, onMessageExtracted, ctx) {
52
+ const parserOptions = ctx.linguiConfig.extractorParserOptions;
53
+ return (0, babel_1.extractFromFileWithBabel)(filename, code, onMessageExtracted, ctx, {
54
+ plugins: (0, babel_1.getBabelParserOptions)(filename, parserOptions),
55
+ }, true);
56
+ },
57
+ },
58
+ ];
38
59
  for (const outFile of Object.keys(bundleResult.metafile.outputs)) {
39
60
  const messages = await (0, extractFromFiles_1.extractFromFiles)([outFile], linguiConfig);
40
61
  const { entryPoint } = bundleResult.metafile.outputs[outFile];
@@ -66,7 +87,7 @@ async function command(linguiConfig, options) {
66
87
  })).statMessage;
67
88
  }
68
89
  stats.push({
69
- entry: (0, utils_1.normalizeSlashes)(path_1.default.relative(linguiConfig.rootDir, entryPoint)),
90
+ entry: (0, normalize_path_1.default)(path_1.default.relative(linguiConfig.rootDir, entryPoint)),
70
91
  content: output,
71
92
  });
72
93
  }
@@ -8,7 +8,7 @@ const commander_1 = require("commander");
8
8
  const conf_1 = require("@lingui/conf");
9
9
  const api_1 = require("./api");
10
10
  const path_1 = __importDefault(require("path"));
11
- const utils_1 = require("./api/utils");
11
+ const normalize_path_1 = __importDefault(require("normalize-path"));
12
12
  async function command(config, options) {
13
13
  options.verbose && console.log("Extracting messages from source files…");
14
14
  const catalogs = await (0, api_1.getCatalogs)(config);
@@ -17,7 +17,7 @@ async function command(config, options) {
17
17
  await Promise.all(catalogs.map(async (catalog) => {
18
18
  const result = await catalog.makeTemplate(Object.assign(Object.assign({}, options), { orderBy: config.orderBy }));
19
19
  if (result) {
20
- catalogStats[(0, utils_1.normalizeSlashes)(path_1.default.relative(config.rootDir, catalog.templateFile))] = Object.keys(result).length;
20
+ catalogStats[(0, normalize_path_1.default)(path_1.default.relative(config.rootDir, catalog.templateFile))] = Object.keys(result).length;
21
21
  }
22
22
  commandSuccess && (commandSuccess = Boolean(result));
23
23
  }));
@@ -4,7 +4,7 @@ export type CliExtractOptions = {
4
4
  files?: string[];
5
5
  clean: boolean;
6
6
  overwrite: boolean;
7
- locale: string;
7
+ locale: string[];
8
8
  prevFormat: string | null;
9
9
  watch?: boolean;
10
10
  };
@@ -12,7 +12,7 @@ const api_1 = require("./api");
12
12
  const stats_1 = require("./api/stats");
13
13
  const help_1 = require("./api/help");
14
14
  const ora_1 = __importDefault(require("ora"));
15
- const utils_1 = require("./api/utils");
15
+ const normalize_path_1 = __importDefault(require("normalize-path"));
16
16
  async function command(config, options) {
17
17
  options.verbose && console.log("Extracting messages from source files…");
18
18
  const catalogs = await (0, api_1.getCatalogs)(config);
@@ -21,7 +21,7 @@ async function command(config, options) {
21
21
  const spinner = (0, ora_1.default)().start();
22
22
  for (let catalog of catalogs) {
23
23
  const result = await catalog.make(Object.assign(Object.assign({}, options), { orderBy: config.orderBy }));
24
- catalogStats[(0, utils_1.normalizeSlashes)(path_1.default.relative(config.rootDir, catalog.path))] = result || {};
24
+ catalogStats[(0, normalize_path_1.default)(path_1.default.relative(config.rootDir, catalog.path))] = result || {};
25
25
  commandSuccess && (commandSuccess = Boolean(result));
26
26
  }
27
27
  if (commandSuccess) {
@@ -61,7 +61,12 @@ exports.default = command;
61
61
  if (require.main === module) {
62
62
  commander_1.program
63
63
  .option("--config <path>", "Path to the config file")
64
- .option("--locale <locale>", "Only extract the specified locale")
64
+ .option("--locale <locale, [...]>", "Only extract the specified locales", (value) => {
65
+ return value
66
+ .split(",")
67
+ .map((s) => s.trim())
68
+ .filter(Boolean);
69
+ })
65
70
  .option("--overwrite", "Overwrite translations for source locale")
66
71
  .option("--clean", "Remove obsolete translations")
67
72
  .option("--debounce <delay>", "Debounces extraction for given amount of milliseconds")
@@ -85,10 +90,13 @@ if (require.main === module) {
85
90
  console.log(chalk_1.default.yellow((0, help_1.helpRun)(`extract --convert-from lingui`)));
86
91
  process.exit(1);
87
92
  }
88
- if (options.locale && !config.locales.includes(options.locale)) {
89
- hasErrors = true;
90
- console.error(`Locale ${chalk_1.default.bold(options.locale)} does not exist.`);
91
- console.error();
93
+ if (options.locale) {
94
+ const missingLocale = options.locale.find((l) => !config.locales.includes(l));
95
+ if (missingLocale) {
96
+ hasErrors = true;
97
+ console.error(`Locale ${chalk_1.default.bold(missingLocale)} does not exist.`);
98
+ console.error();
99
+ }
92
100
  }
93
101
  if (hasErrors)
94
102
  process.exit(1);
@@ -7,7 +7,7 @@ const fs_1 = __importDefault(require("fs"));
7
7
  const path_1 = require("path");
8
8
  const pofile_1 = __importDefault(require("pofile"));
9
9
  const https_1 = __importDefault(require("https"));
10
- const glob_1 = __importDefault(require("glob"));
10
+ const glob_1 = require("glob");
11
11
  const date_fns_1 = require("date-fns");
12
12
  const EXPLICIT_ID_FLAG = "js-lingui-explicit-id";
13
13
  const EXPLICIT_ID_AND_CONTEXT_FLAG = "js-lingui-explicit-id-and-context";
@@ -262,7 +262,7 @@ function poPathsPerLocale(config) {
262
262
  const path = "".concat(catalog.path.replace(/{locale}/g, locale).replace(/{name}/g, "*"), ".po");
263
263
  // If {name} is present (replaced by *), list all the existing POs
264
264
  if (path.includes("*")) {
265
- paths[locale] = paths[locale].concat(glob_1.default.sync(path));
265
+ paths[locale] = paths[locale].concat((0, glob_1.globSync)(path));
266
266
  }
267
267
  else {
268
268
  paths[locale].push(path);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingui/cli",
3
- "version": "4.11.4",
3
+ "version": "5.0.0-next.1",
4
4
  "description": "CLI for working wit message catalogs",
5
5
  "keywords": [
6
6
  "cli",
@@ -53,11 +53,12 @@
53
53
  "@babel/parser": "^7.21.2",
54
54
  "@babel/runtime": "^7.21.0",
55
55
  "@babel/types": "^7.21.2",
56
- "@lingui/babel-plugin-extract-messages": "4.11.4",
57
- "@lingui/conf": "4.11.4",
58
- "@lingui/core": "4.11.4",
59
- "@lingui/format-po": "4.11.4",
60
- "@lingui/message-utils": "4.11.4",
56
+ "@lingui/babel-plugin-extract-messages": "^5.0.0-next.1",
57
+ "@lingui/babel-plugin-lingui-macro": "^5.0.0-next.1",
58
+ "@lingui/conf": "^5.0.0-next.1",
59
+ "@lingui/core": "^5.0.0-next.1",
60
+ "@lingui/format-po": "^5.0.0-next.1",
61
+ "@lingui/message-utils": "^5.0.0-next.1",
61
62
  "babel-plugin-macros": "^3.0.1",
62
63
  "chalk": "^4.1.0",
63
64
  "chokidar": "3.5.1",
@@ -65,10 +66,10 @@
65
66
  "commander": "^10.0.0",
66
67
  "convert-source-map": "^2.0.0",
67
68
  "date-fns": "^3.6.0",
68
- "esbuild": "^0.17.10",
69
- "glob": "^7.1.4",
69
+ "esbuild": "^0.21.5",
70
+ "glob": "^11.0.0",
70
71
  "inquirer": "^7.3.3",
71
- "micromatch": "^4.0.2",
72
+ "micromatch": "^4.0.7",
72
73
  "normalize-path": "^3.0.0",
73
74
  "ora": "^5.1.0",
74
75
  "pathe": "^1.1.0",
@@ -79,14 +80,12 @@
79
80
  "source-map": "^0.8.0-beta.0"
80
81
  },
81
82
  "devDependencies": {
82
- "@lingui/jest-mocks": "*",
83
- "@lingui/macro": "4.11.4",
83
+ "@lingui/jest-mocks": "^3.0.3",
84
84
  "@types/convert-source-map": "^2.0.0",
85
- "@types/glob": "^8.1.0",
86
85
  "@types/micromatch": "^4.0.1",
87
86
  "@types/normalize-path": "^3.0.0",
88
87
  "mock-fs": "^5.2.0",
89
88
  "mockdate": "^3.0.5"
90
89
  },
91
- "gitHead": "43d4e671360e8e5f1b820e4e061c1926d95c120b"
90
+ "gitHead": "7936155f7b29ecdc6191042a9a2e363962ab482d"
92
91
  }
@@ -1,13 +0,0 @@
1
- type PackageJson = {
2
- dependencies?: Record<string, string>;
3
- devDependencies?: Record<string, string>;
4
- peerDependencies?: Record<string, string>;
5
- optionalDependencies?: Record<string, string>;
6
- };
7
- export declare function buildExternalizeFilter({ includeDeps, excludeDeps, packageJson, }: {
8
- includeDeps: string[];
9
- excludeDeps: string[];
10
- packageJson: PackageJson;
11
- }): (id: string) => boolean;
12
- export declare function getPackageJson(rootDir: string): Promise<PackageJson>;
13
- export {};
@@ -1,47 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getPackageJson = exports.buildExternalizeFilter = void 0;
7
- const node_fs_1 = __importDefault(require("node:fs"));
8
- function createPackageRegExp(packageName) {
9
- return new RegExp("^" + packageName + "(?:\\/.+)?");
10
- }
11
- function packages(packages, includeDeps) {
12
- return Object.keys(packages || {})
13
- .filter((packageName) => {
14
- return !includeDeps.some((incl) => packageName.startsWith(incl));
15
- })
16
- .map(createPackageRegExp);
17
- }
18
- function buildExternalizeFilter({ includeDeps, excludeDeps, packageJson, }) {
19
- const external = [
20
- ...packages(packageJson.dependencies, includeDeps),
21
- ...packages(packageJson.devDependencies, includeDeps),
22
- ...packages(packageJson.peerDependencies, includeDeps),
23
- ...packages(packageJson.optionalDependencies, includeDeps),
24
- ...excludeDeps.map(createPackageRegExp),
25
- ];
26
- return (id) => external.some((regExp) => {
27
- return regExp.test(id);
28
- });
29
- }
30
- exports.buildExternalizeFilter = buildExternalizeFilter;
31
- async function getPackageJson(rootDir) {
32
- const { default: pkgUp } = await import("pkg-up");
33
- const packageJsonPath = await pkgUp({
34
- cwd: rootDir,
35
- });
36
- if (!packageJsonPath) {
37
- throw new Error("We could not able to find your package.json file. " +
38
- "Check that `rootDir` is pointing to the folder with package.json");
39
- }
40
- try {
41
- return JSON.parse(await node_fs_1.default.promises.readFile(packageJsonPath, "utf-8"));
42
- }
43
- catch (e) {
44
- throw new Error(`Unable to read package.json file at path ${packageJsonPath}. \n\n Error: ${e.message}`);
45
- }
46
- }
47
- exports.getPackageJson = getPackageJson;