@lingui/cli 5.9.1 → 6.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/api/ProgramExit.js +1 -5
  2. package/dist/api/catalog/extractFromFiles.d.ts +4 -4
  3. package/dist/api/catalog/extractFromFiles.js +38 -32
  4. package/dist/api/catalog/getCatalogDependentFiles.d.ts +1 -1
  5. package/dist/api/catalog/getCatalogDependentFiles.js +8 -47
  6. package/dist/api/catalog/getCatalogs.d.ts +2 -2
  7. package/dist/api/catalog/getCatalogs.js +35 -44
  8. package/dist/api/catalog/getFallbackListForLocale.js +5 -8
  9. package/dist/api/catalog/getTranslationsForCatalog.d.ts +1 -1
  10. package/dist/api/catalog/getTranslationsForCatalog.js +9 -13
  11. package/dist/api/catalog/mergeCatalog.d.ts +3 -3
  12. package/dist/api/catalog/mergeCatalog.js +13 -21
  13. package/dist/api/catalog.d.ts +15 -15
  14. package/dist/api/catalog.js +48 -45
  15. package/dist/api/compile/compileLocale.d.ts +3 -3
  16. package/dist/api/compile/compileLocale.js +28 -33
  17. package/dist/api/compile.js +13 -49
  18. package/dist/api/extractors/babel.d.ts +2 -2
  19. package/dist/api/extractors/babel.js +52 -45
  20. package/dist/api/extractors/index.js +6 -13
  21. package/dist/api/formats/formatterWrapper.d.ts +2 -2
  22. package/dist/api/formats/formatterWrapper.js +10 -12
  23. package/dist/api/formats/index.d.ts +3 -4
  24. package/dist/api/formats/index.js +5 -44
  25. package/dist/api/getPathsForCompileWatcher.d.ts +7 -0
  26. package/dist/api/getPathsForCompileWatcher.js +15 -0
  27. package/dist/api/getPathsForExtractWatcher.d.ts +8 -0
  28. package/dist/api/getPathsForExtractWatcher.js +14 -0
  29. package/dist/api/help.js +5 -7
  30. package/dist/api/index.d.ts +7 -7
  31. package/dist/api/index.js +7 -36
  32. package/dist/api/logger.d.ts +1 -1
  33. package/dist/api/logger.js +1 -2
  34. package/dist/api/messages.d.ts +2 -2
  35. package/dist/api/messages.js +5 -12
  36. package/dist/api/pseudoLocalize.js +3 -9
  37. package/dist/api/resolveWorkersOptions.js +3 -9
  38. package/dist/api/rethrownError.js +2 -5
  39. package/dist/api/stats.d.ts +3 -2
  40. package/dist/api/stats.js +7 -16
  41. package/dist/api/typedPool.d.ts +6 -0
  42. package/dist/api/typedPool.js +16 -0
  43. package/dist/api/types.js +1 -2
  44. package/dist/api/utils.d.ts +2 -2
  45. package/dist/api/utils.js +24 -41
  46. package/dist/api/workerLogger.d.ts +2 -2
  47. package/dist/api/workerLogger.js +2 -8
  48. package/dist/api/workerPools.d.ts +3 -0
  49. package/dist/api/workerPools.js +7 -0
  50. package/dist/extract-experimental/buildIncludeDepsFilter.js +1 -4
  51. package/dist/extract-experimental/bundleSource.d.ts +3 -2
  52. package/dist/extract-experimental/bundleSource.js +10 -13
  53. package/dist/extract-experimental/constants.js +2 -5
  54. package/dist/extract-experimental/extractFromBundleAndWrite.d.ts +3 -4
  55. package/dist/extract-experimental/extractFromBundleAndWrite.js +11 -17
  56. package/dist/extract-experimental/getExperimentalCatalogs.d.ts +4 -3
  57. package/dist/extract-experimental/getExperimentalCatalogs.js +10 -15
  58. package/dist/extract-experimental/linguiEsbuildPlugin.js +12 -19
  59. package/dist/extract-experimental/resolveCatalogPath.d.ts +1 -1
  60. package/dist/extract-experimental/resolveCatalogPath.js +7 -14
  61. package/dist/extract-experimental/resolveTemplatePath.js +7 -10
  62. package/dist/extract-experimental/workers/extractWorker.d.ts +5 -3
  63. package/dist/extract-experimental/workers/extractWorker.js +7 -10
  64. package/dist/extract-experimental/workers/extractWorkerWrapper.prod.d.ts +8 -0
  65. package/dist/extract-experimental/workers/extractWorkerWrapper.prod.js +2 -0
  66. package/dist/extract-experimental/writeCatalogs.d.ts +2 -2
  67. package/dist/extract-experimental/writeCatalogs.js +15 -22
  68. package/dist/index.js +1 -5
  69. package/dist/lingui-compile.d.ts +1 -1
  70. package/dist/lingui-compile.js +45 -59
  71. package/dist/lingui-extract-experimental.d.ts +3 -2
  72. package/dist/lingui-extract-experimental.js +58 -62
  73. package/dist/lingui-extract-template.d.ts +5 -4
  74. package/dist/lingui-extract-template.js +25 -27
  75. package/dist/lingui-extract.d.ts +3 -4
  76. package/dist/lingui-extract.js +62 -69
  77. package/dist/lingui.js +5 -10
  78. package/dist/services/translationIO/segment-converters.d.ts +1 -1
  79. package/dist/services/translationIO/segment-converters.js +16 -20
  80. package/dist/services/translationIO/translationio-api.d.ts +11 -7
  81. package/dist/services/translationIO/translationio-api.js +2 -19
  82. package/dist/services/translationIO.d.ts +4 -4
  83. package/dist/services/translationIO.js +28 -35
  84. package/dist/workers/compileWorker.d.ts +8 -11
  85. package/dist/workers/compileWorker.js +30 -36
  86. package/dist/workers/compileWorkerWrapper.prod.d.ts +7 -0
  87. package/dist/workers/compileWorkerWrapper.prod.js +2 -0
  88. package/dist/workers/extractWorker.d.ts +2 -3
  89. package/dist/workers/extractWorker.js +5 -12
  90. package/dist/workers/extractWorkerWrapper.prod.d.ts +6 -0
  91. package/dist/workers/extractWorkerWrapper.prod.js +2 -0
  92. package/package.json +26 -43
  93. package/dist/api/extractWorkerPool.d.ts +0 -1
  94. package/dist/api/extractWorkerPool.js +0 -8
  95. package/dist/api/extractors/typescript.d.ts +0 -3
  96. package/dist/api/extractors/typescript.js +0 -11
  97. package/dist/extract-experimental/getEntryPoints.d.ts +0 -1
  98. package/dist/extract-experimental/getEntryPoints.js +0 -7
@@ -1,36 +1,34 @@
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.orderByMessage = exports.Catalog = void 0;
7
- exports.cleanObsolete = cleanObsolete;
8
- exports.order = order;
9
- exports.writeCompiled = writeCompiled;
10
- const fs_1 = __importDefault(require("fs"));
11
- const path_1 = __importDefault(require("path"));
12
- const glob_1 = require("glob");
13
- const normalize_path_1 = __importDefault(require("normalize-path"));
14
- const getTranslationsForCatalog_1 = require("./catalog/getTranslationsForCatalog");
15
- const mergeCatalog_1 = require("./catalog/mergeCatalog");
16
- const extractFromFiles_1 = require("./catalog/extractFromFiles");
17
- const utils_1 = require("./utils");
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { globSync } from "node:fs";
4
+ import normalize from "normalize-path";
5
+ import { getTranslationsForCatalog, } from "./catalog/getTranslationsForCatalog.js";
6
+ import { mergeCatalog } from "./catalog/mergeCatalog.js";
7
+ import { extractFromFiles, extractFromFilesWithWorkerPool, } from "./catalog/extractFromFiles.js";
8
+ import { isDirectory, makePathRegexSafe, normalizeRelativePath, replacePlaceholders, writeFile, } from "./utils.js";
18
9
  const LOCALE = "{locale}";
19
10
  const LOCALE_SUFFIX_RE = /\{locale\}.*$/;
20
- class Catalog {
11
+ export class Catalog {
12
+ config;
13
+ name;
14
+ path;
15
+ include;
16
+ exclude;
17
+ format;
18
+ templateFile;
21
19
  constructor({ name, path, include, templatePath, format, exclude = [] }, config) {
22
20
  this.config = config;
23
21
  this.name = name;
24
- this.path = (0, utils_1.normalizeRelativePath)(path);
25
- this.include = include.map(utils_1.normalizeRelativePath);
26
- this.exclude = [this.localeDir, ...exclude.map(utils_1.normalizeRelativePath)];
22
+ this.path = normalizeRelativePath(path);
23
+ this.include = include.map(normalizeRelativePath);
24
+ this.exclude = [this.localeDir, ...exclude.map(normalizeRelativePath)];
27
25
  this.format = format;
28
26
  this.templateFile =
29
27
  templatePath ||
30
28
  getTemplatePath(this.format.getTemplateExtension(), this.path);
31
29
  }
32
30
  getFilename(locale) {
33
- return ((0, utils_1.replacePlaceholders)(this.path, { locale }) +
31
+ return (replacePlaceholders(this.path, { locale }) +
34
32
  this.format.getCatalogExtension());
35
33
  }
36
34
  async make(options) {
@@ -73,14 +71,14 @@ class Catalog {
73
71
  async collect(options = {}) {
74
72
  let paths = this.sourcePaths;
75
73
  if (options.files) {
76
- options.files = options.files.map((p) => (0, utils_1.makePathRegexSafe)((0, normalize_path_1.default)(p, false)));
74
+ options.files = options.files.map((p) => makePathRegexSafe(normalize(p, false)));
77
75
  const regex = new RegExp(options.files.join("|"), "i");
78
- paths = paths.filter((path) => regex.test((0, normalize_path_1.default)(path)));
76
+ paths = paths.filter((path) => regex.test(normalize(path)));
79
77
  }
80
78
  if (options.workerPool) {
81
- return await (0, extractFromFiles_1.extractFromFilesWithWorkerPool)(options.workerPool, paths, this.config);
79
+ return await extractFromFilesWithWorkerPool(options.workerPool, paths, this.config);
82
80
  }
83
- return await (0, extractFromFiles_1.extractFromFiles)(paths, this.config);
81
+ return await extractFromFiles(paths, this.config);
84
82
  }
85
83
  /*
86
84
  *
@@ -105,28 +103,33 @@ class Catalog {
105
103
  merge(prevCatalogs, nextCatalog, options) {
106
104
  return Object.fromEntries(Object.entries(prevCatalogs).map(([locale, prevCatalog]) => [
107
105
  locale,
108
- (0, mergeCatalog_1.mergeCatalog)(prevCatalog, nextCatalog, this.config.sourceLocale === locale, options),
106
+ mergeCatalog(prevCatalog, nextCatalog, this.config.sourceLocale === locale, options),
109
107
  ]));
110
108
  }
111
109
  async getTranslations(locale, options) {
112
- return await (0, getTranslationsForCatalog_1.getTranslationsForCatalog)(this, locale, options);
110
+ return await getTranslationsForCatalog(this, locale, options);
113
111
  }
114
112
  async write(locale, messages) {
115
113
  const filename = this.getFilename(locale);
116
- const created = !fs_1.default.existsSync(filename);
114
+ const created = !fs.existsSync(filename);
117
115
  await this.format.write(filename, messages, locale);
118
116
  return [created, filename];
119
117
  }
120
118
  async writeTemplate(messages) {
121
119
  const filename = this.templateFile;
122
- await this.format.write(filename, messages, undefined);
120
+ await this.format.write(filename, messages);
123
121
  }
124
122
  async read(locale) {
125
123
  return await this.format.read(this.getFilename(locale), locale);
126
124
  }
127
125
  async readAll(locales = this.locales) {
128
126
  const res = {};
129
- await Promise.all(locales.map(async (locale) => (res[locale] = await this.read(locale))));
127
+ await Promise.all(locales.map(async (locale) => {
128
+ const catalog = await this.read(locale);
129
+ if (catalog) {
130
+ res[locale] = catalog;
131
+ }
132
+ }));
130
133
  // statement above will save locales in object in undetermined order
131
134
  // resort here to have keys order the same as in locales definition
132
135
  return this.locales.reduce((acc, locale) => {
@@ -135,21 +138,20 @@ class Catalog {
135
138
  }, {});
136
139
  }
137
140
  async readTemplate() {
138
- const filename = this.templateFile;
139
- return await this.format.read(filename, undefined);
141
+ return await this.format.read(this.templateFile, undefined);
140
142
  }
141
143
  get sourcePaths() {
142
144
  const includeGlobs = this.include.map((includePath) => {
143
- const isDir = (0, utils_1.isDirectory)(includePath);
145
+ const isDir = isDirectory(includePath);
144
146
  /**
145
147
  * glob library results from absolute patterns such as /foo/* are mounted onto the root setting using path.join.
146
148
  * On windows, this will by default result in /foo/* matching C:\foo\bar.txt.
147
149
  */
148
150
  return isDir
149
- ? (0, normalize_path_1.default)(path_1.default.resolve(process.cwd(), includePath === "/" ? "" : includePath, "**/*.*"))
151
+ ? normalize(path.resolve(process.cwd(), includePath === "/" ? "" : includePath, "**/*.*"))
150
152
  : includePath;
151
153
  });
152
- return (0, glob_1.globSync)(includeGlobs, { ignore: this.exclude, mark: true });
154
+ return globSync(includeGlobs, { exclude: this.exclude });
153
155
  }
154
156
  get localeDir() {
155
157
  const localePatternIndex = this.path.indexOf(LOCALE);
@@ -162,19 +164,18 @@ class Catalog {
162
164
  return this.config.locales;
163
165
  }
164
166
  }
165
- exports.Catalog = Catalog;
166
167
  function getTemplatePath(ext, path) {
167
168
  return path.replace(LOCALE_SUFFIX_RE, "messages" + ext);
168
169
  }
169
- function cleanObsolete(messages) {
170
+ export function cleanObsolete(messages) {
170
171
  return Object.fromEntries(Object.entries(messages).filter(([, message]) => !message.obsolete));
171
172
  }
172
- function order(by, catalog) {
173
+ export function order(by, catalog) {
173
174
  const orderByFn = typeof by === "function"
174
175
  ? by
175
176
  : {
176
177
  messageId: orderByMessageId,
177
- message: exports.orderByMessage,
178
+ message: orderByMessage,
178
179
  origin: orderByOrigin,
179
180
  }[by];
180
181
  return Object.keys(catalog)
@@ -195,6 +196,9 @@ const orderByMessageId = (a, b) => {
195
196
  return a.messageId.localeCompare(b.messageId);
196
197
  };
197
198
  const orderByOrigin = (a, b) => {
199
+ if (!a.entry.origin || !b.entry.origin) {
200
+ return 0;
201
+ }
198
202
  function getFirstOrigin(entry) {
199
203
  const sortedOrigins = entry.origin.sort((a, b) => {
200
204
  if (a[0] < b[0])
@@ -217,7 +221,7 @@ const orderByOrigin = (a, b) => {
217
221
  return 1;
218
222
  return 0;
219
223
  };
220
- async function writeCompiled(path, locale, compiledCatalog, namespace) {
224
+ export async function writeCompiled(path, locale, compiledCatalog, namespace) {
221
225
  let ext;
222
226
  switch (namespace) {
223
227
  case "es":
@@ -230,11 +234,11 @@ async function writeCompiled(path, locale, compiledCatalog, namespace) {
230
234
  default:
231
235
  ext = "js";
232
236
  }
233
- const filename = `${(0, utils_1.replacePlaceholders)(path, { locale })}.${ext}`;
234
- await (0, utils_1.writeFile)(filename, compiledCatalog);
237
+ const filename = `${replacePlaceholders(path, { locale })}.${ext}`;
238
+ await writeFile(filename, compiledCatalog);
235
239
  return filename;
236
240
  }
237
- const orderByMessage = (a, b) => {
241
+ export const orderByMessage = (a, b) => {
238
242
  // hardcoded en-US locale to have consistent sorting
239
243
  // @see https://github.com/lingui/js-lingui/pull/1808
240
244
  const collator = new Intl.Collator("en-US");
@@ -244,4 +248,3 @@ const orderByMessage = (a, b) => {
244
248
  const bCtxt = b.entry.context || "";
245
249
  return collator.compare(aMsg, bMsg) || collator.compare(aCtxt, bCtxt);
246
250
  };
247
- exports.orderByMessage = orderByMessage;
@@ -1,5 +1,5 @@
1
- import { Catalog } from "../catalog";
1
+ import { Catalog } from "../catalog.js";
2
2
  import { LinguiConfigNormalized } from "@lingui/conf";
3
- import { CliCompileOptions } from "../../lingui-compile";
4
- import { Logger } from "../logger";
3
+ import { CliCompileOptions } from "../../lingui-compile.js";
4
+ import { Logger } from "../logger.js";
5
5
  export declare function compileLocale(catalogs: Catalog[], locale: string, options: CliCompileOptions, config: LinguiConfigNormalized, doMerge: boolean, logger: Logger): Promise<void>;
@@ -1,31 +1,25 @@
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.compileLocale = compileLocale;
7
- const catalog_1 = require("../catalog");
8
- const picocolors_1 = __importDefault(require("picocolors"));
9
- const getCatalogs_1 = require("../catalog/getCatalogs");
10
- const ProgramExit_1 = require("../ProgramExit");
11
- const compile_1 = require("../compile");
12
- const normalize_path_1 = __importDefault(require("normalize-path"));
13
- const path_1 = __importDefault(require("path"));
14
- const messages_1 = require("../messages");
15
- const getTranslationsForCatalog_1 = require("../catalog/getTranslationsForCatalog");
16
- async function compileLocale(catalogs, locale, options, config, doMerge, logger) {
1
+ import { writeCompiled } from "../catalog.js";
2
+ import { styleText } from "node:util";
3
+ import { getMergedCatalogPath } from "../catalog/getCatalogs.js";
4
+ import { ProgramExit } from "../ProgramExit.js";
5
+ import { createCompiledCatalog } from "../compile.js";
6
+ import normalizePath from "normalize-path";
7
+ import nodepath from "path";
8
+ import { createCompilationErrorMessage } from "../messages.js";
9
+ import { getTranslationsForCatalog } from "../catalog/getTranslationsForCatalog.js";
10
+ export async function compileLocale(catalogs, locale, options, config, doMerge, logger) {
17
11
  let mergedCatalogs = {};
18
12
  for (const catalog of catalogs) {
19
- const { messages, missing: missingMessages } = await (0, getTranslationsForCatalog_1.getTranslationsForCatalog)(catalog, locale, {
13
+ const { messages, missing: missingMessages } = await getTranslationsForCatalog(catalog, locale, {
20
14
  fallbackLocales: config.fallbackLocales,
21
15
  sourceLocale: config.sourceLocale,
22
16
  });
23
17
  if (!options.allowEmpty &&
24
18
  locale !== config.pseudoLocale &&
25
19
  missingMessages.length > 0) {
26
- logger.error(picocolors_1.default.red(`Error: Failed to compile catalog for locale ${picocolors_1.default.bold(locale)}!`));
20
+ logger.error(styleText("red", `Error: Failed to compile catalog for locale ${styleText("bold", locale)}!`));
27
21
  if (options.verbose) {
28
- logger.error(picocolors_1.default.red("Missing translations:"));
22
+ logger.error(styleText("red", "Missing translations:"));
29
23
  missingMessages.forEach((missing) => {
30
24
  const source = missing.source || missing.source === missing.id
31
25
  ? `: (${missing.source})`
@@ -34,24 +28,24 @@ async function compileLocale(catalogs, locale, options, config, doMerge, logger)
34
28
  });
35
29
  }
36
30
  else {
37
- logger.error(picocolors_1.default.red(`Missing ${missingMessages.length} translation(s)`));
31
+ logger.error(styleText("red", `Missing ${missingMessages.length} translation(s)`));
38
32
  }
39
- logger.error();
40
- throw new ProgramExit_1.ProgramExit();
33
+ logger.error("");
34
+ throw new ProgramExit();
41
35
  }
42
36
  if (doMerge) {
43
- mergedCatalogs = Object.assign(Object.assign({}, mergedCatalogs), messages);
37
+ mergedCatalogs = { ...mergedCatalogs, ...messages };
44
38
  }
45
39
  else {
46
40
  if (!(await compileAndWrite(locale, config, options, catalog.path, messages, logger))) {
47
- throw new ProgramExit_1.ProgramExit();
41
+ throw new ProgramExit();
48
42
  }
49
43
  }
50
44
  }
51
45
  if (doMerge) {
52
- const result = await compileAndWrite(locale, config, options, await (0, getCatalogs_1.getMergedCatalogPath)(config), mergedCatalogs, logger);
46
+ const result = await compileAndWrite(locale, config, options, await getMergedCatalogPath(config), mergedCatalogs, logger);
53
47
  if (!result) {
54
- throw new ProgramExit_1.ProgramExit();
48
+ throw new ProgramExit();
55
49
  }
56
50
  }
57
51
  }
@@ -59,7 +53,7 @@ async function compileAndWrite(locale, config, options, writePath, messages, log
59
53
  const namespace = options.typescript
60
54
  ? "ts"
61
55
  : options.namespace || config.compileNamespace;
62
- const { source: compiledCatalog, errors } = (0, compile_1.createCompiledCatalog)(locale, messages, {
56
+ const { source: compiledCatalog, errors } = createCompiledCatalog(locale, messages, {
63
57
  strict: false,
64
58
  namespace,
65
59
  outputPrefix: options.outputPrefix,
@@ -67,19 +61,20 @@ async function compileAndWrite(locale, config, options, writePath, messages, log
67
61
  compilerBabelOptions: config.compilerBabelOptions,
68
62
  });
69
63
  if (errors.length) {
70
- let message = (0, messages_1.createCompilationErrorMessage)(locale, errors);
64
+ let message = createCompilationErrorMessage(locale, errors);
71
65
  if (options.failOnCompileError) {
72
66
  message += `These errors fail command execution because \`--strict\` option passed`;
73
- logger.error(picocolors_1.default.red(message));
67
+ logger.error(styleText("red", message));
74
68
  return false;
75
69
  }
76
70
  else {
77
71
  message += `You can fail command execution on these errors by passing \`--strict\` option`;
78
- logger.error(picocolors_1.default.red(message));
72
+ logger.error(styleText("red", message));
79
73
  }
80
74
  }
81
- let compiledPath = await (0, catalog_1.writeCompiled)(writePath, locale, compiledCatalog, namespace);
82
- compiledPath = (0, normalize_path_1.default)(path_1.default.relative(config.rootDir, compiledPath));
83
- options.verbose && logger.error(picocolors_1.default.green(`${locale} ⇒ ${compiledPath}`));
75
+ let compiledPath = await writeCompiled(writePath, locale, compiledCatalog, namespace);
76
+ compiledPath = normalizePath(nodepath.relative(config.rootDir, compiledPath));
77
+ options.verbose &&
78
+ logger.error(styleText("green", `${locale} ⇒ ${compiledPath}`));
84
79
  return true;
85
80
  }
@@ -1,48 +1,8 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.createCompiledCatalog = createCompiledCatalog;
40
- exports.compile = compile;
41
- const t = __importStar(require("@babel/types"));
42
- const generator_1 = __importDefault(require("@babel/generator"));
43
- const compileMessage_1 = require("@lingui/message-utils/compileMessage");
44
- const pseudoLocalize_1 = __importDefault(require("./pseudoLocalize"));
45
- function createCompiledCatalog(locale, messages, options) {
1
+ import * as t from "@babel/types";
2
+ import { generate } from "@babel/generator";
3
+ import { compileMessageOrThrow, } from "@lingui/message-utils/compileMessage";
4
+ import pseudoLocalize from "./pseudoLocalize.js";
5
+ export function createCompiledCatalog(locale, messages, options) {
46
6
  const { strict = false, namespace = "cjs", pseudoLocale, compilerBabelOptions = {}, outputPrefix = "/*eslint-disable*/", } = options;
47
7
  const shouldPseudolocalize = locale === pseudoLocale;
48
8
  const errors = [];
@@ -69,9 +29,13 @@ function createCompiledCatalog(locale, messages, options) {
69
29
  const ast = buildExportStatement(
70
30
  //build JSON.parse(<compiledMessages>) statement
71
31
  t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [t.stringLiteral(JSON.stringify(compiledMessages))]), namespace);
72
- const code = (0, generator_1.default)(ast, Object.assign({ minified: true, jsescOption: {
32
+ const code = generate(ast, {
33
+ minified: true,
34
+ jsescOption: {
73
35
  minimal: true,
74
- } }, compilerBabelOptions)).code;
36
+ },
37
+ ...compilerBabelOptions,
38
+ }).code;
75
39
  return { source: `${outputPrefix}` + code, errors };
76
40
  }
77
41
  function buildExportStatement(expression, namespace) {
@@ -116,6 +80,6 @@ function buildExportStatement(expression, namespace) {
116
80
  * Compile string message into AST tree. Message format is parsed/compiled into
117
81
  * JS arrays, which are handled in client.
118
82
  */
119
- function compile(message, shouldPseudolocalize = false) {
120
- return (0, compileMessage_1.compileMessageOrThrow)(message, (value) => shouldPseudolocalize ? (0, pseudoLocalize_1.default)(value) : value);
83
+ export function compile(message, shouldPseudolocalize = false) {
84
+ return compileMessageOrThrow(message, (value) => shouldPseudolocalize ? pseudoLocalize(value) : value);
121
85
  }
@@ -1,5 +1,5 @@
1
1
  import { ParserOptions } from "@babel/core";
2
- import { ExtractorType, LinguiConfig, ExtractedMessage, ExtractorCtx } from "@lingui/conf";
2
+ import { ExtractorType, LinguiConfigNormalized, ExtractedMessage, ExtractorCtx } from "@lingui/conf";
3
3
  export declare const babelRe: RegExp;
4
4
  /**
5
5
  * @public
@@ -27,6 +27,6 @@ export declare const babelRe: RegExp;
27
27
  * ```
28
28
  */
29
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" | "deferredImportEvaluation" | "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" | "sourcePhaseImports" | "throwExpressions" | "topLevelAwait" | "v8intrinsic" | "decorators" | "estree" | "importAttributes" | "moduleAttributes" | "optionalChainingAssign" | "pipelineOperator" | "recordAndTuple" | "typescript"))[];
30
+ export declare function getBabelParserOptions(filename: string, parserOptions: LinguiConfigNormalized["extractorParserOptions"]): (import("@babel/parser").ParserPluginWithOptions | ("decimal" | "asyncDoExpressions" | "asyncGenerators" | "bigInt" | "classPrivateMethods" | "classPrivateProperties" | "classProperties" | "classStaticBlock" | "decorators-legacy" | "deferredImportEvaluation" | "decoratorAutoAccessors" | "destructuringPrivate" | "doExpressions" | "dynamicImport" | "explicitResourceManagement" | "exportDefaultFrom" | "exportNamespaceFrom" | "flow" | "flowComments" | "functionBind" | "functionSent" | "importMeta" | "jsx" | "logicalAssignment" | "importAssertions" | "importReflection" | "moduleBlocks" | "moduleStringNames" | "nullishCoalescingOperator" | "numericSeparator" | "objectRestSpread" | "optionalCatchBinding" | "optionalChaining" | "partialApplication" | "placeholders" | "privateIn" | "regexpUnicodeSets" | "sourcePhaseImports" | "throwExpressions" | "topLevelAwait" | "v8intrinsic" | "decorators" | "estree" | "importAttributes" | "moduleAttributes" | "optionalChainingAssign" | "pipelineOperator" | "recordAndTuple" | "typescript"))[];
31
31
  declare const extractor: ExtractorType;
32
32
  export default extractor;
@@ -1,20 +1,29 @@
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.babelRe = void 0;
7
- exports.extractFromFileWithBabel = extractFromFileWithBabel;
8
- exports.getBabelParserOptions = getBabelParserOptions;
9
- const core_1 = require("@babel/core");
10
- const babel_plugin_extract_messages_1 = __importDefault(require("@lingui/babel-plugin-extract-messages"));
11
- const babel_plugin_lingui_macro_1 = __importDefault(require("@lingui/babel-plugin-lingui-macro"));
12
- exports.babelRe = new RegExp("\\.(" +
13
- [...core_1.DEFAULT_EXTENSIONS, ".ts", ".mts", ".cts", ".tsx"]
1
+ import { DEFAULT_EXTENSIONS, transformAsync } from "@babel/core";
2
+ import linguiExtractMessages from "@lingui/babel-plugin-extract-messages";
3
+ import linguiMacroPlugin from "@lingui/babel-plugin-lingui-macro";
4
+ export const babelRe = new RegExp("\\.(" +
5
+ [...DEFAULT_EXTENSIONS, ".ts", ".mts", ".cts", ".tsx"]
14
6
  .map((ext) => ext.slice(1))
15
7
  .join("|") +
16
8
  ")$", "i");
17
- const inlineSourceMapsRE = new RegExp(/\/[/*][#@]\s+sourceMappingURL=data:application\/json;(?:charset:utf-8;)?base64,/i);
9
+ const inlineSourceMapsRE = new RegExp(/\/[/*][#@]\s+sourceMappingURL=data:application\/json;(?:charset[:=]utf-8;)?base64,([A-Za-z0-9+/=]+)/i);
10
+ const globalInlineSourceMapsRE = new RegExp(inlineSourceMapsRE.source, "gi");
11
+ const extractInlineSourceMap = (code) => {
12
+ let base64Data;
13
+ globalInlineSourceMapsRE.lastIndex = 0;
14
+ for (const match of code.matchAll(globalInlineSourceMapsRE)) {
15
+ base64Data = match[1];
16
+ }
17
+ if (!base64Data)
18
+ return null;
19
+ try {
20
+ const jsonString = Buffer.from(base64Data, "base64").toString("utf-8");
21
+ return JSON.parse(jsonString);
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ };
18
27
  /**
19
28
  * Create a source mapper which could read original positions
20
29
  * from either inline sourcemaps or from external passed as `sourceMaps` argument.
@@ -25,33 +34,28 @@ const inlineSourceMapsRE = new RegExp(/\/[/*][#@]\s+sourceMappingURL=data:applic
25
34
  * @param sourceMaps Raw Sourcemaps object to mapping from. Check the https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap
26
35
  */
27
36
  async function createSourceMapper(code, sourceMaps) {
28
- let sourceMapsConsumer;
29
- if (sourceMaps) {
30
- const { SourceMapConsumer } = await import("source-map");
31
- sourceMapsConsumer = await new SourceMapConsumer(sourceMaps);
32
- }
33
- else if (code.search(inlineSourceMapsRE) != -1) {
34
- const { SourceMapConsumer } = await import("source-map");
35
- const { fromSource } = await import("convert-source-map");
36
- const t = fromSource(code).toObject();
37
- sourceMapsConsumer = await new SourceMapConsumer(t);
37
+ const map = sourceMaps ?? extractInlineSourceMap(code);
38
+ if (!map) {
39
+ return {
40
+ destroy: () => { },
41
+ originalPositionFor: (origin) => origin,
42
+ };
38
43
  }
44
+ const { SourceMapConsumer } = await import("source-map");
45
+ const sourceMapsConsumer = await new SourceMapConsumer(map);
39
46
  return {
40
- destroy: () => {
41
- if (sourceMapsConsumer) {
42
- sourceMapsConsumer.destroy();
43
- }
44
- },
47
+ destroy: () => sourceMapsConsumer.destroy(),
45
48
  originalPositionFor: (origin) => {
46
- if (!sourceMapsConsumer) {
47
- return origin;
48
- }
49
49
  const [_, line, column] = origin;
50
50
  const mappedPosition = sourceMapsConsumer.originalPositionFor({
51
51
  line,
52
- column,
52
+ column: column,
53
53
  });
54
- return [mappedPosition.source, mappedPosition.line, mappedPosition.column];
54
+ return [
55
+ mappedPosition.source,
56
+ mappedPosition.line,
57
+ mappedPosition.column,
58
+ ];
55
59
  },
56
60
  };
57
61
  }
@@ -80,21 +84,21 @@ async function createSourceMapper(code, sourceMaps) {
80
84
  * }
81
85
  * ```
82
86
  */
83
- async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, parserOpts, skipMacroPlugin = false) {
84
- const mapper = await createSourceMapper(code, ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps);
85
- await (0, core_1.transformAsync)(code, {
87
+ export async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, parserOpts, skipMacroPlugin = false) {
88
+ const mapper = await createSourceMapper(code, ctx?.sourceMaps);
89
+ await transformAsync(code, {
86
90
  // don't generate code
87
91
  code: false,
88
92
  babelrc: false,
89
93
  configFile: false,
90
94
  filename: filename,
91
- inputSourceMap: ctx === null || ctx === void 0 ? void 0 : ctx.sourceMaps,
95
+ inputSourceMap: ctx?.sourceMaps,
92
96
  parserOpts,
93
97
  plugins: [
94
98
  ...(!skipMacroPlugin
95
99
  ? [
96
100
  [
97
- babel_plugin_lingui_macro_1.default,
101
+ linguiMacroPlugin,
98
102
  {
99
103
  extract: true,
100
104
  linguiConfig: ctx.linguiConfig,
@@ -103,10 +107,13 @@ async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx,
103
107
  ]
104
108
  : []),
105
109
  [
106
- babel_plugin_extract_messages_1.default,
110
+ linguiExtractMessages,
107
111
  {
108
112
  onMessageExtracted: (msg) => {
109
- return onMessageExtracted(Object.assign(Object.assign({}, msg), { origin: mapper.originalPositionFor(msg.origin) }));
113
+ return onMessageExtracted({
114
+ ...msg,
115
+ origin: mapper.originalPositionFor(msg.origin),
116
+ });
110
117
  },
111
118
  },
112
119
  ],
@@ -114,7 +121,7 @@ async function extractFromFileWithBabel(filename, code, onMessageExtracted, ctx,
114
121
  });
115
122
  mapper.destroy();
116
123
  }
117
- function getBabelParserOptions(filename, parserOptions) {
124
+ export function getBabelParserOptions(filename, parserOptions) {
118
125
  // https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
119
126
  const parserPlugins = [
120
127
  "importAttributes", // stage3
@@ -133,7 +140,7 @@ function getBabelParserOptions(filename, parserOptions) {
133
140
  }
134
141
  else {
135
142
  parserPlugins.push("decorators");
136
- if (parserOptions === null || parserOptions === void 0 ? void 0 : parserOptions.flow) {
143
+ if (parserOptions?.flow) {
137
144
  parserPlugins.push("flow");
138
145
  }
139
146
  }
@@ -144,7 +151,7 @@ function getBabelParserOptions(filename, parserOptions) {
144
151
  }
145
152
  const extractor = {
146
153
  match(filename) {
147
- return exports.babelRe.test(filename);
154
+ return babelRe.test(filename);
148
155
  },
149
156
  async extract(filename, code, onMessageExtracted, ctx) {
150
157
  const parserOptions = ctx.linguiConfig.extractorParserOptions;
@@ -153,4 +160,4 @@ const extractor = {
153
160
  });
154
161
  },
155
162
  };
156
- exports.default = extractor;
163
+ export default extractor;
@@ -1,20 +1,13 @@
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.default = extract;
7
- const promises_1 = __importDefault(require("fs/promises"));
8
- const babel_1 = __importDefault(require("./babel"));
9
- const DEFAULT_EXTRACTORS = [babel_1.default];
10
- async function extract(filename, onMessageExtracted, linguiConfig) {
11
- var _a;
12
- const extractorsToExtract = (_a = linguiConfig.extractors) !== null && _a !== void 0 ? _a : DEFAULT_EXTRACTORS;
1
+ import fs from "fs/promises";
2
+ import babel from "./babel.js";
3
+ const DEFAULT_EXTRACTORS = [babel];
4
+ export default async function extract(filename, onMessageExtracted, linguiConfig) {
5
+ const extractorsToExtract = linguiConfig.extractors ?? DEFAULT_EXTRACTORS;
13
6
  for (const ext of extractorsToExtract) {
14
7
  if (!ext.match(filename))
15
8
  continue;
16
9
  try {
17
- const file = await promises_1.default.readFile(filename);
10
+ const file = await fs.readFile(filename);
18
11
  await ext.extract(filename, file.toString(), onMessageExtracted, {
19
12
  linguiConfig,
20
13
  });
@@ -5,6 +5,6 @@ export declare class FormatterWrapper {
5
5
  constructor(f: CatalogFormatter, sourceLocale: string);
6
6
  getCatalogExtension(): string;
7
7
  getTemplateExtension(): string;
8
- write(filename: string, catalog: CatalogType, locale: string): Promise<void>;
9
- read(filename: string, locale: string): Promise<CatalogType | null>;
8
+ write(filename: string, catalog: CatalogType, locale?: string): Promise<void>;
9
+ read(filename: string, locale: string | undefined): Promise<CatalogType | undefined>;
10
10
  }