@lang-tag/cli 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -4,13 +4,14 @@ import fs, { readFileSync, existsSync } from "fs";
4
4
  import { writeFile, readFile } from "fs/promises";
5
5
  import JSON5 from "json5";
6
6
  import * as path from "path";
7
- import path__default, { sep, join, dirname as dirname$1 } from "path";
7
+ import path__default, { sep, join, dirname } from "path";
8
8
  import { globby } from "globby";
9
- import path$1, { resolve, dirname } from "pathe";
9
+ import path$1, { resolve } from "pathe";
10
10
  import { pathToFileURL, fileURLToPath } from "url";
11
- import { N as NamespaceCollector, $ as $LT_ReadFileContent, a as $LT_ReadJSON, b as $LT_WriteJSON, c as $LT_EnsureDirectoryExists, d as $LT_WriteFileWithDirs } from "./namespace-collector-DCruv_PK.js";
11
+ import "case";
12
12
  import * as process$1 from "node:process";
13
13
  import process__default from "node:process";
14
+ import { f as flexibleImportAlgorithm, N as NamespaceCollector, $ as $LT_ReadFileContent, a as $LT_ReadJSON, b as $LT_WriteJSON, c as $LT_EnsureDirectoryExists, d as $LT_WriteFileWithDirs } from "./flexible-import-algorithm-C-S1c742.js";
14
15
  import * as acorn from "acorn";
15
16
  import micromatch from "micromatch";
16
17
  import chokidar from "chokidar";
@@ -479,7 +480,7 @@ function isConfigSame(c1, c2) {
479
480
  return false;
480
481
  }
481
482
  const CONFIG_FILE_NAME = ".lang-tag.config.js";
482
- const EXPORTS_FILE_NAME = ".lang-tag.exports.json";
483
+ const EXPORTS_FILE_NAME = "lang-tags.json";
483
484
  const LANG_TAG_DEFAULT_CONFIG = {
484
485
  tagName: "lang",
485
486
  isLibrary: false,
@@ -508,12 +509,18 @@ const LANG_TAG_DEFAULT_CONFIG = {
508
509
  import: {
509
510
  dir: "src/lang-libraries",
510
511
  tagImportPath: 'import { lang } from "@/my-lang-tag-path"',
511
- onImport: ({ importedRelativePath, fileGenerationData }, actions) => {
512
- const exportIndex = (fileGenerationData.index || 0) + 1;
513
- fileGenerationData.index = exportIndex;
514
- actions.setFile(path$1.basename(importedRelativePath));
515
- actions.setExportName(`translations${exportIndex}`);
516
- }
512
+ onImport: flexibleImportAlgorithm({
513
+ filePath: {
514
+ includePackageInPath: true
515
+ }
516
+ })
517
+ // onImport: ({importedRelativePath, fileGenerationData}: LangTagCLIOnImportParams, actions)=> {
518
+ // const exportIndex = (fileGenerationData.index || 0) + 1;
519
+ // fileGenerationData.index = exportIndex;
520
+ //
521
+ // actions.setFile(path.basename(importedRelativePath));
522
+ // actions.setExportName(`translations${exportIndex}`);
523
+ // }
517
524
  },
518
525
  translationArgPosition: 1,
519
526
  onConfigGeneration: async (event) => {
@@ -1022,19 +1029,19 @@ function deepMergeTranslations(target, source) {
1022
1029
  async function $LT_WriteToCollections({ config, collections, logger, clean }) {
1023
1030
  await config.collect.collector.preWrite(clean);
1024
1031
  const changedCollections = [];
1025
- for (let namespace of Object.keys(collections)) {
1026
- if (!namespace) {
1032
+ for (let collectionName of Object.keys(collections)) {
1033
+ if (!collectionName) {
1027
1034
  continue;
1028
1035
  }
1029
- const filePath = await config.collect.collector.resolveCollectionFilePath(namespace);
1036
+ const filePath = await config.collect.collector.resolveCollectionFilePath(collectionName);
1030
1037
  let originalJSON = {};
1031
1038
  try {
1032
1039
  originalJSON = await $LT_ReadJSON(filePath);
1033
1040
  } catch (e) {
1034
- await config.collect.collector.onMissingCollection(namespace);
1041
+ await config.collect.collector.onMissingCollection(collectionName);
1035
1042
  }
1036
- if (deepMergeTranslations(originalJSON, collections[namespace])) {
1037
- changedCollections.push(namespace);
1043
+ if (deepMergeTranslations(originalJSON, collections[collectionName])) {
1044
+ changedCollections.push(collectionName);
1038
1045
  await $LT_WriteJSON(filePath, originalJSON);
1039
1046
  }
1040
1047
  }
@@ -1073,28 +1080,18 @@ async function $LT_WriteAsExportFile({ config, logger, files }) {
1073
1080
  if (!packageJson) {
1074
1081
  throw new Error("package.json not found");
1075
1082
  }
1076
- const langTagFiles = {};
1077
- for (const file of files) {
1078
- langTagFiles[file.relativeFilePath] = {
1079
- matches: file.tags.map((tag) => {
1080
- let T = config.translationArgPosition === 1 ? tag.parameter1Text : tag.parameter2Text;
1081
- let C = config.translationArgPosition === 1 ? tag.parameter2Text : tag.parameter1Text;
1082
- if (!T) T = "{}";
1083
- if (!C) C = "{}";
1084
- return {
1085
- translations: T,
1086
- config: C,
1087
- variableName: tag.variableName
1088
- };
1089
- })
1090
- };
1091
- }
1092
- const data = {
1093
- language: config.baseLanguageCode,
1094
- packageName: packageJson.name || "",
1095
- files: langTagFiles
1083
+ const exportData = {
1084
+ baseLanguageCode: config.baseLanguageCode,
1085
+ files: files.map(({ relativeFilePath, tags }) => ({
1086
+ relativeFilePath,
1087
+ tags: tags.map((tag) => ({
1088
+ variableName: tag.variableName,
1089
+ config: tag.parameterConfig,
1090
+ translations: tag.parameterTranslations
1091
+ }))
1092
+ }))
1096
1093
  };
1097
- await $LT_WriteJSON(EXPORTS_FILE_NAME, data);
1094
+ await writeFile(EXPORTS_FILE_NAME, JSON.stringify(exportData), "utf-8");
1098
1095
  logger.success(`Written {file}`, { file: EXPORTS_FILE_NAME });
1099
1096
  }
1100
1097
  async function $LT_GroupTagsToCollections({ logger, files, config }) {
@@ -1465,97 +1462,171 @@ async function $LT_CMD_InitConfig() {
1465
1462
  logger.error(error?.message);
1466
1463
  }
1467
1464
  }
1468
- function $LT_CollectNodeModulesExportFilePaths(logger) {
1465
+ async function $LT_CollectExportFiles(logger) {
1469
1466
  const nodeModulesPath = path$1.join(process__default.cwd(), "node_modules");
1470
1467
  if (!fs.existsSync(nodeModulesPath)) {
1471
1468
  logger.error('"node_modules" directory not found');
1472
1469
  return [];
1473
1470
  }
1474
- function findExportJson(dir, depth = 0, maxDepth = 3) {
1475
- if (depth > maxDepth) return [];
1476
- let results = [];
1477
- try {
1478
- const files = fs.readdirSync(dir);
1479
- for (const file of files) {
1480
- const fullPath = path$1.join(dir, file);
1481
- const stat = fs.statSync(fullPath);
1482
- if (stat.isDirectory()) {
1483
- results = results.concat(findExportJson(fullPath, depth + 1, maxDepth));
1484
- } else if (file === EXPORTS_FILE_NAME) {
1485
- results.push(fullPath);
1486
- }
1471
+ const results = [];
1472
+ try {
1473
+ const exportFiles = await globby([
1474
+ `node_modules/**/${EXPORTS_FILE_NAME}`
1475
+ ], {
1476
+ cwd: process__default.cwd(),
1477
+ onlyFiles: true,
1478
+ ignore: ["**/node_modules/**/node_modules/**"],
1479
+ deep: 4
1480
+ });
1481
+ for (const exportFile of exportFiles) {
1482
+ const fullExportPath = path$1.resolve(exportFile);
1483
+ const packageJsonPath = findPackageJsonForExport(fullExportPath, nodeModulesPath);
1484
+ if (packageJsonPath) {
1485
+ results.push({
1486
+ exportPath: fullExportPath,
1487
+ packageJsonPath
1488
+ });
1489
+ } else {
1490
+ logger.warn("Found export file but could not match package.json: {exportPath}", {
1491
+ exportPath: fullExportPath
1492
+ });
1487
1493
  }
1488
- } catch (error) {
1489
- logger.error('Error reading directory "{dir}": {error}', {
1490
- dir,
1491
- error: String(error)
1492
- });
1493
1494
  }
1494
- return results;
1495
+ logger.debug("Found {count} export files with matching package.json in node_modules", {
1496
+ count: results.length
1497
+ });
1498
+ } catch (error) {
1499
+ logger.error("Error scanning node_modules with globby: {error}", {
1500
+ error: String(error)
1501
+ });
1495
1502
  }
1496
- return findExportJson(nodeModulesPath);
1503
+ return results;
1497
1504
  }
1498
- async function $LT_ImportLibraries(config, logger) {
1499
- const files = $LT_CollectNodeModulesExportFilePaths(logger);
1500
- const generationFiles = {};
1501
- for (const filePath of files) {
1502
- const exportData = await $LT_ReadJSON(filePath);
1503
- for (let langTagFilePath in exportData.files) {
1504
- const fileGenerationData = {};
1505
- const matches = exportData.files[langTagFilePath].matches;
1506
- for (let match of matches) {
1507
- let parsedTranslations = typeof match.translations === "string" ? JSON5.parse(match.translations) : match.translations;
1508
- let parsedConfig = typeof match.config === "string" ? JSON5.parse(match.config) : match.config === void 0 ? {} : match.config;
1509
- let file = langTagFilePath;
1510
- let exportName = match.variableName || "";
1511
- config.import.onImport({
1512
- packageName: exportData.packageName,
1513
- importedRelativePath: langTagFilePath,
1514
- originalExportName: match.variableName,
1515
- translations: parsedTranslations,
1516
- config: parsedConfig,
1517
- fileGenerationData
1518
- }, {
1519
- setFile: (f) => {
1520
- file = f;
1521
- },
1522
- setExportName: (name) => {
1523
- exportName = name;
1524
- },
1525
- setConfig: (newConfig) => {
1526
- parsedConfig = newConfig;
1527
- }
1528
- });
1529
- if (!file || !exportName) {
1530
- throw new Error(`[lang-tag] onImport did not set fileName or exportName for package: ${exportData.packageName}, file: '${file}' (original: '${langTagFilePath}'), exportName: '${exportName}' (original: ${match.variableName})`);
1531
- }
1532
- let exports = generationFiles[file];
1533
- if (!exports) {
1534
- exports = {};
1535
- generationFiles[file] = exports;
1536
- }
1537
- const param1 = config.translationArgPosition === 1 ? parsedTranslations : parsedConfig;
1538
- const param2 = config.translationArgPosition === 1 ? parsedConfig : parsedTranslations;
1539
- exports[exportName] = `${config.tagName}(${JSON5.stringify(param1, void 0, 4)}, ${JSON5.stringify(param2, void 0, 4)})`;
1505
+ function findPackageJsonForExport(exportPath, nodeModulesPath) {
1506
+ const relativePath = path$1.relative(nodeModulesPath, exportPath);
1507
+ const pathParts = relativePath.split(path$1.sep);
1508
+ if (pathParts.length < 2) {
1509
+ return null;
1510
+ }
1511
+ if (pathParts[0].startsWith("@")) {
1512
+ if (pathParts.length >= 3) {
1513
+ const packageDir = path$1.join(nodeModulesPath, pathParts[0], pathParts[1]);
1514
+ const packageJsonPath = path$1.join(packageDir, "package.json");
1515
+ if (fs.existsSync(packageJsonPath)) {
1516
+ return packageJsonPath;
1540
1517
  }
1541
1518
  }
1519
+ } else {
1520
+ const packageDir = path$1.join(nodeModulesPath, pathParts[0]);
1521
+ const packageJsonPath = path$1.join(packageDir, "package.json");
1522
+ if (fs.existsSync(packageJsonPath)) {
1523
+ return packageJsonPath;
1524
+ }
1542
1525
  }
1543
- for (let fileName of Object.keys(generationFiles)) {
1526
+ return null;
1527
+ }
1528
+ const __filename = fileURLToPath(import.meta.url);
1529
+ const __dirname = dirname(__filename);
1530
+ const templatePath = join(__dirname, "templates", "import", "imported-tag.mustache");
1531
+ const template = readFileSync(templatePath, "utf-8");
1532
+ function renderTemplate$1(data) {
1533
+ return mustache.render(template, data, {}, { escape: (text) => text });
1534
+ }
1535
+ async function generateImportFiles(config, logger, importManager) {
1536
+ const importedFiles = importManager.getImportedFiles();
1537
+ for (const importedFile of importedFiles) {
1544
1538
  const filePath = resolve(
1545
1539
  process$1.cwd(),
1546
1540
  config.import.dir,
1547
- fileName
1541
+ importedFile.pathRelativeToImportDir
1548
1542
  );
1549
- const exports = Object.entries(generationFiles[fileName]).map(([name, tag]) => {
1550
- return `export const ${name} = ${tag};`;
1551
- }).join("\n\n");
1552
- const content = `${config.import.tagImportPath}
1553
-
1554
- ${exports}`;
1543
+ const processedExports = importedFile.tags.map((tag) => {
1544
+ const parameter1 = config.translationArgPosition === 1 ? tag.translations : tag.config;
1545
+ const parameter2 = config.translationArgPosition === 1 ? tag.config : tag.translations;
1546
+ const hasParameter2 = parameter2 !== null && parameter2 !== void 0 && (typeof parameter2 !== "object" || Object.keys(parameter2).length > 0);
1547
+ return {
1548
+ name: tag.variableName,
1549
+ parameter1: JSON5.stringify(parameter1, void 0, 4),
1550
+ parameter2: hasParameter2 ? JSON5.stringify(parameter2, void 0, 4) : null,
1551
+ hasParameter2,
1552
+ config: {
1553
+ tagName: config.tagName
1554
+ }
1555
+ };
1556
+ });
1557
+ const templateData = {
1558
+ tagImportPath: config.import.tagImportPath,
1559
+ exports: processedExports
1560
+ };
1561
+ const content = renderTemplate$1(templateData);
1555
1562
  await $LT_EnsureDirectoryExists(dirname(filePath));
1556
1563
  await writeFile(filePath, content, "utf-8");
1557
- logger.success('Imported node_modules file: "{fileName}"', { fileName });
1564
+ logger.success('Created tag file: "{file}"', { file: importedFile.pathRelativeToImportDir });
1565
+ }
1566
+ }
1567
+ class ImportManager {
1568
+ importedFiles = [];
1569
+ constructor() {
1570
+ this.importedFiles = [];
1571
+ }
1572
+ importTag(pathRelativeToImportDir, tag) {
1573
+ if (!pathRelativeToImportDir) {
1574
+ throw new Error(`pathRelativeToImportDir required, got: ${pathRelativeToImportDir}`);
1575
+ }
1576
+ if (!tag?.variableName) {
1577
+ throw new Error(`tag.variableName required, got: ${tag?.variableName}`);
1578
+ }
1579
+ if (!this.isValidJavaScriptIdentifier(tag.variableName)) {
1580
+ throw new Error(`Invalid JavaScript identifier: "${tag.variableName}". Variable names must start with a letter, underscore, or dollar sign, and contain only letters, digits, underscores, and dollar signs.`);
1581
+ }
1582
+ if (tag.translations == null) {
1583
+ throw new Error(`tag.translations required`);
1584
+ }
1585
+ let importedFile = this.importedFiles.find(
1586
+ (file) => file.pathRelativeToImportDir === pathRelativeToImportDir
1587
+ );
1588
+ if (importedFile) {
1589
+ const duplicateTag = importedFile.tags.find(
1590
+ (existingTag) => existingTag.variableName === tag.variableName
1591
+ );
1592
+ if (duplicateTag) {
1593
+ throw new Error(`Duplicate variable name "${tag.variableName}" in file "${pathRelativeToImportDir}". Variable names must be unique within the same file.`);
1594
+ }
1595
+ }
1596
+ if (!importedFile) {
1597
+ importedFile = { pathRelativeToImportDir, tags: [] };
1598
+ this.importedFiles.push(importedFile);
1599
+ }
1600
+ importedFile.tags.push(tag);
1601
+ }
1602
+ getImportedFiles() {
1603
+ return [...this.importedFiles];
1604
+ }
1605
+ getImportedFilesCount() {
1606
+ return this.importedFiles.length;
1558
1607
  }
1608
+ hasImportedFiles() {
1609
+ return this.importedFiles.length > 0;
1610
+ }
1611
+ isValidJavaScriptIdentifier(name) {
1612
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
1613
+ }
1614
+ }
1615
+ async function $LT_ImportLibraries(config, logger) {
1616
+ const exportFiles = await $LT_CollectExportFiles(logger);
1617
+ const importManager = new ImportManager();
1618
+ let exports = [];
1619
+ for (const { exportPath, packageJsonPath } of exportFiles) {
1620
+ const exportData = await $LT_ReadJSON(exportPath);
1621
+ const packageJSON = await $LT_ReadJSON(packageJsonPath);
1622
+ exports.push({ packageJSON, exportData });
1623
+ }
1624
+ config.import.onImport({ exports, importManager, logger, langTagConfig: config });
1625
+ if (!importManager.hasImportedFiles()) {
1626
+ logger.warn("No tags were imported from any library files");
1627
+ return;
1628
+ }
1629
+ await generateImportFiles(config, logger, importManager);
1559
1630
  if (config.import.onImportFinish) config.import.onImportFinish();
1560
1631
  }
1561
1632
  async function $LT_ImportTranslations() {
@@ -1565,15 +1636,15 @@ async function $LT_ImportTranslations() {
1565
1636
  await $LT_ImportLibraries(config, logger);
1566
1637
  logger.success("Successfully imported translations from libraries.");
1567
1638
  }
1568
- function renderTemplate(template, data) {
1569
- return mustache.render(template, data, {}, { escape: (text) => text });
1639
+ function renderTemplate(template2, data) {
1640
+ return mustache.render(template2, data, {}, { escape: (text) => text });
1570
1641
  }
1571
1642
  function loadTemplate(templateName) {
1572
- const __filename = fileURLToPath(import.meta.url);
1573
- const __dirname = dirname$1(__filename);
1574
- const templatePath = join(__dirname, "template", `${templateName}.mustache`);
1643
+ const __filename2 = fileURLToPath(import.meta.url);
1644
+ const __dirname2 = dirname(__filename2);
1645
+ const templatePath2 = join(__dirname2, "templates", "tag", `${templateName}.mustache`);
1575
1646
  try {
1576
- return readFileSync(templatePath, "utf-8");
1647
+ return readFileSync(templatePath2, "utf-8");
1577
1648
  } catch (error) {
1578
1649
  throw new Error(`Failed to load template ${templateName}: ${error}`);
1579
1650
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lang-tag/cli",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -0,0 +1 @@
1
+ -
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Imported library translations
3
+ *
4
+ * You can modify these translations as needed. On next import:
5
+ * - Your changes will be preserved ( for now only translations values are preserved )
6
+ * - New translations will be added
7
+ * - Unused translations will be commented out
8
+ */
9
+ {{tagImportPath}}
10
+
11
+ {{#exports}}
12
+ export const {{name}} = {{config.tagName}}({{parameter1}}{{#hasParameter2}}, {{parameter2}}{{/hasParameter2}});
13
+
14
+ {{/exports}}
@@ -1,95 +0,0 @@
1
- import { mkdir, writeFile, readFile, rm } from "fs/promises";
2
- import { dirname, resolve } from "path";
3
- import path, { resolve as resolve$1 } from "pathe";
4
- import process__default from "node:process";
5
- class TranslationsCollector {
6
- config;
7
- logger;
8
- }
9
- async function $LT_EnsureDirectoryExists(filePath) {
10
- await mkdir(filePath, { recursive: true });
11
- }
12
- async function $LT_RemoveDirectory(dirPath) {
13
- try {
14
- await rm(dirPath, { recursive: true, force: true });
15
- } catch (error) {
16
- }
17
- }
18
- async function $LT_RemoveFile(filePath) {
19
- try {
20
- await rm(filePath, { force: true });
21
- } catch (error) {
22
- }
23
- }
24
- async function $LT_WriteJSON(filePath, data) {
25
- await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
26
- }
27
- async function $LT_ReadJSON(filePath) {
28
- const content = await readFile(filePath, "utf-8");
29
- return JSON.parse(content);
30
- }
31
- async function $LT_WriteFileWithDirs(filePath, content) {
32
- const dir = dirname(filePath);
33
- try {
34
- await mkdir(dir, { recursive: true });
35
- } catch (error) {
36
- }
37
- await writeFile(filePath, content, "utf-8");
38
- }
39
- async function $LT_ReadFileContent(relativeFilePath) {
40
- const cwd = process.cwd();
41
- const absolutePath = resolve(cwd, relativeFilePath);
42
- return await readFile(absolutePath, "utf-8");
43
- }
44
- class NamespaceCollector extends TranslationsCollector {
45
- clean;
46
- languageDirectory;
47
- aggregateCollection(namespace) {
48
- return namespace;
49
- }
50
- transformTag(tag) {
51
- return tag;
52
- }
53
- async preWrite(clean) {
54
- this.clean = clean;
55
- this.languageDirectory = path.join(this.config.localesDirectory, this.config.baseLanguageCode);
56
- if (clean) {
57
- this.logger.info("Cleaning output directory...");
58
- await $LT_RemoveDirectory(this.languageDirectory);
59
- }
60
- await $LT_EnsureDirectoryExists(this.languageDirectory);
61
- }
62
- async resolveCollectionFilePath(collectionName) {
63
- return resolve$1(
64
- process__default.cwd(),
65
- this.languageDirectory,
66
- collectionName + ".json"
67
- );
68
- }
69
- async onMissingCollection(collectionName) {
70
- if (!this.clean) {
71
- this.logger.warn(`Original namespace file "{namespace}.json" not found. A new one will be created.`, { namespace: collectionName });
72
- }
73
- }
74
- async postWrite(changedCollections) {
75
- if (!changedCollections?.length) {
76
- this.logger.info("No changes were made based on the current configuration and files");
77
- return;
78
- }
79
- const n = changedCollections.map((n2) => `"${n2}.json"`).join(", ");
80
- this.logger.success("Updated namespaces {outputDir} ({namespaces})", {
81
- outputDir: this.config.localesDirectory,
82
- namespaces: n
83
- });
84
- }
85
- }
86
- export {
87
- $LT_ReadFileContent as $,
88
- NamespaceCollector as N,
89
- TranslationsCollector as T,
90
- $LT_ReadJSON as a,
91
- $LT_WriteJSON as b,
92
- $LT_EnsureDirectoryExists as c,
93
- $LT_WriteFileWithDirs as d,
94
- $LT_RemoveFile as e
95
- };
@@ -1,94 +0,0 @@
1
- "use strict";
2
- const promises = require("fs/promises");
3
- const path = require("path");
4
- const path$1 = require("pathe");
5
- const process$1 = require("node:process");
6
- class TranslationsCollector {
7
- config;
8
- logger;
9
- }
10
- async function $LT_EnsureDirectoryExists(filePath) {
11
- await promises.mkdir(filePath, { recursive: true });
12
- }
13
- async function $LT_RemoveDirectory(dirPath) {
14
- try {
15
- await promises.rm(dirPath, { recursive: true, force: true });
16
- } catch (error) {
17
- }
18
- }
19
- async function $LT_RemoveFile(filePath) {
20
- try {
21
- await promises.rm(filePath, { force: true });
22
- } catch (error) {
23
- }
24
- }
25
- async function $LT_WriteJSON(filePath, data) {
26
- await promises.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
27
- }
28
- async function $LT_ReadJSON(filePath) {
29
- const content = await promises.readFile(filePath, "utf-8");
30
- return JSON.parse(content);
31
- }
32
- async function $LT_WriteFileWithDirs(filePath, content) {
33
- const dir = path.dirname(filePath);
34
- try {
35
- await promises.mkdir(dir, { recursive: true });
36
- } catch (error) {
37
- }
38
- await promises.writeFile(filePath, content, "utf-8");
39
- }
40
- async function $LT_ReadFileContent(relativeFilePath) {
41
- const cwd = process.cwd();
42
- const absolutePath = path.resolve(cwd, relativeFilePath);
43
- return await promises.readFile(absolutePath, "utf-8");
44
- }
45
- class NamespaceCollector extends TranslationsCollector {
46
- clean;
47
- languageDirectory;
48
- aggregateCollection(namespace) {
49
- return namespace;
50
- }
51
- transformTag(tag) {
52
- return tag;
53
- }
54
- async preWrite(clean) {
55
- this.clean = clean;
56
- this.languageDirectory = path$1.join(this.config.localesDirectory, this.config.baseLanguageCode);
57
- if (clean) {
58
- this.logger.info("Cleaning output directory...");
59
- await $LT_RemoveDirectory(this.languageDirectory);
60
- }
61
- await $LT_EnsureDirectoryExists(this.languageDirectory);
62
- }
63
- async resolveCollectionFilePath(collectionName) {
64
- return path$1.resolve(
65
- process$1.cwd(),
66
- this.languageDirectory,
67
- collectionName + ".json"
68
- );
69
- }
70
- async onMissingCollection(collectionName) {
71
- if (!this.clean) {
72
- this.logger.warn(`Original namespace file "{namespace}.json" not found. A new one will be created.`, { namespace: collectionName });
73
- }
74
- }
75
- async postWrite(changedCollections) {
76
- if (!changedCollections?.length) {
77
- this.logger.info("No changes were made based on the current configuration and files");
78
- return;
79
- }
80
- const n = changedCollections.map((n2) => `"${n2}.json"`).join(", ");
81
- this.logger.success("Updated namespaces {outputDir} ({namespaces})", {
82
- outputDir: this.config.localesDirectory,
83
- namespaces: n
84
- });
85
- }
86
- }
87
- exports.$LT_EnsureDirectoryExists = $LT_EnsureDirectoryExists;
88
- exports.$LT_ReadFileContent = $LT_ReadFileContent;
89
- exports.$LT_ReadJSON = $LT_ReadJSON;
90
- exports.$LT_RemoveFile = $LT_RemoveFile;
91
- exports.$LT_WriteFileWithDirs = $LT_WriteFileWithDirs;
92
- exports.$LT_WriteJSON = $LT_WriteJSON;
93
- exports.NamespaceCollector = NamespaceCollector;
94
- exports.TranslationsCollector = TranslationsCollector;
File without changes