@intlayer/chokidar 5.4.1 → 5.5.0-canary.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 (132) hide show
  1. package/dist/cjs/chokidar/watcher.cjs +3 -3
  2. package/dist/cjs/chokidar/watcher.cjs.map +1 -1
  3. package/dist/cjs/cleanOutputDir.cjs +7 -9
  4. package/dist/cjs/cleanOutputDir.cjs.map +1 -1
  5. package/dist/cjs/fetchDistantDictionaries.cjs +4 -3
  6. package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
  7. package/dist/cjs/filterDictionaryLocales.cjs +58 -0
  8. package/dist/cjs/filterDictionaryLocales.cjs.map +1 -0
  9. package/dist/cjs/getBuiltUnmergedDictionariesPath.cjs +51 -0
  10. package/dist/cjs/getBuiltUnmergedDictionariesPath.cjs.map +1 -0
  11. package/dist/cjs/getContentDeclarationFileTemplate/cjsTemplate.md +9 -0
  12. package/dist/cjs/getContentDeclarationFileTemplate/esmTemplate.md +9 -0
  13. package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs +62 -0
  14. package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -0
  15. package/dist/cjs/getContentDeclarationFileTemplate/tsTemplate.md +8 -0
  16. package/dist/cjs/index.cjs +21 -6
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/listGitFiles.cjs +98 -0
  19. package/dist/cjs/listGitFiles.cjs.map +1 -0
  20. package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -23
  21. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  22. package/dist/cjs/loadDictionaries/loadDistantDictionaries.cjs +7 -1
  23. package/dist/cjs/loadDictionaries/loadDistantDictionaries.cjs.map +1 -1
  24. package/dist/cjs/mergeDictionaries.cjs +43 -23
  25. package/dist/cjs/mergeDictionaries.cjs.map +1 -1
  26. package/dist/cjs/prepareIntlayer.cjs +1 -1
  27. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  28. package/dist/cjs/processPerLocaleDictionary.cjs +49 -0
  29. package/dist/cjs/processPerLocaleDictionary.cjs.map +1 -0
  30. package/dist/cjs/reduceDictionaryContent/applyMask.cjs +50 -0
  31. package/dist/cjs/reduceDictionaryContent/applyMask.cjs.map +1 -0
  32. package/dist/cjs/reduceDictionaryContent/buildMask.cjs +49 -0
  33. package/dist/cjs/reduceDictionaryContent/buildMask.cjs.map +1 -0
  34. package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs +35 -0
  35. package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -0
  36. package/dist/cjs/transpiler/declaration_file_to_dictionary/i18next_dictionary/writeDictionary.cjs +4 -4
  37. package/dist/cjs/transpiler/declaration_file_to_dictionary/i18next_dictionary/writeDictionary.cjs.map +1 -1
  38. package/dist/cjs/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.cjs +56 -8
  39. package/dist/cjs/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.cjs.map +1 -1
  40. package/dist/cjs/transpiler/declaration_file_to_dictionary/reactIntl_dictionary/writeDictionary.cjs +4 -4
  41. package/dist/cjs/transpiler/declaration_file_to_dictionary/reactIntl_dictionary/writeDictionary.cjs.map +1 -1
  42. package/dist/cjs/transpiler/dictionary_to_main/createDictionaryEntryPoint.cjs +21 -1
  43. package/dist/cjs/transpiler/dictionary_to_main/createDictionaryEntryPoint.cjs.map +1 -1
  44. package/dist/cjs/writeContentDeclaration/formatCode.cjs +61 -0
  45. package/dist/cjs/writeContentDeclaration/formatCode.cjs.map +1 -0
  46. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +36 -37
  47. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  48. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +377 -0
  49. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -0
  50. package/dist/esm/chokidar/watcher.mjs +5 -5
  51. package/dist/esm/chokidar/watcher.mjs.map +1 -1
  52. package/dist/esm/cleanOutputDir.mjs +7 -9
  53. package/dist/esm/cleanOutputDir.mjs.map +1 -1
  54. package/dist/esm/fetchDistantDictionaries.mjs +5 -4
  55. package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
  56. package/dist/esm/filterDictionaryLocales.mjs +37 -0
  57. package/dist/esm/filterDictionaryLocales.mjs.map +1 -0
  58. package/dist/esm/getBuiltUnmergedDictionariesPath.mjs +17 -0
  59. package/dist/esm/getBuiltUnmergedDictionariesPath.mjs.map +1 -0
  60. package/dist/esm/getContentDeclarationFileTemplate/cjsTemplate.md +9 -0
  61. package/dist/esm/getContentDeclarationFileTemplate/esmTemplate.md +9 -0
  62. package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs +37 -0
  63. package/dist/esm/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs.map +1 -0
  64. package/dist/esm/getContentDeclarationFileTemplate/tsTemplate.md +8 -0
  65. package/dist/esm/index.mjs +21 -9
  66. package/dist/esm/index.mjs.map +1 -1
  67. package/dist/esm/listGitFiles.mjs +64 -0
  68. package/dist/esm/listGitFiles.mjs.map +1 -0
  69. package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -13
  70. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  71. package/dist/esm/loadDictionaries/loadDistantDictionaries.mjs +7 -1
  72. package/dist/esm/loadDictionaries/loadDistantDictionaries.mjs.map +1 -1
  73. package/dist/esm/mergeDictionaries.mjs +42 -22
  74. package/dist/esm/mergeDictionaries.mjs.map +1 -1
  75. package/dist/esm/prepareIntlayer.mjs +3 -3
  76. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  77. package/dist/esm/processPerLocaleDictionary.mjs +25 -0
  78. package/dist/esm/processPerLocaleDictionary.mjs.map +1 -0
  79. package/dist/esm/reduceDictionaryContent/applyMask.mjs +26 -0
  80. package/dist/esm/reduceDictionaryContent/applyMask.mjs.map +1 -0
  81. package/dist/esm/reduceDictionaryContent/buildMask.mjs +24 -0
  82. package/dist/esm/reduceDictionaryContent/buildMask.mjs.map +1 -0
  83. package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs +11 -0
  84. package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -0
  85. package/dist/esm/transpiler/declaration_file_to_dictionary/i18next_dictionary/writeDictionary.mjs +4 -4
  86. package/dist/esm/transpiler/declaration_file_to_dictionary/i18next_dictionary/writeDictionary.mjs.map +1 -1
  87. package/dist/esm/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.mjs +54 -8
  88. package/dist/esm/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.mjs.map +1 -1
  89. package/dist/esm/transpiler/declaration_file_to_dictionary/reactIntl_dictionary/writeDictionary.mjs +4 -4
  90. package/dist/esm/transpiler/declaration_file_to_dictionary/reactIntl_dictionary/writeDictionary.mjs.map +1 -1
  91. package/dist/esm/transpiler/dictionary_to_main/createDictionaryEntryPoint.mjs +21 -1
  92. package/dist/esm/transpiler/dictionary_to_main/createDictionaryEntryPoint.mjs.map +1 -1
  93. package/dist/esm/writeContentDeclaration/formatCode.mjs +37 -0
  94. package/dist/esm/writeContentDeclaration/formatCode.mjs.map +1 -0
  95. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +35 -36
  96. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  97. package/dist/esm/writeContentDeclaration/writeJSFile.mjs +345 -0
  98. package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -0
  99. package/dist/types/chokidar/watcher.d.ts.map +1 -1
  100. package/dist/types/cleanOutputDir.d.ts.map +1 -1
  101. package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
  102. package/dist/types/filterDictionaryLocales.d.ts +4 -0
  103. package/dist/types/filterDictionaryLocales.d.ts.map +1 -0
  104. package/dist/types/getBuiltUnmergedDictionariesPath.d.ts +5 -0
  105. package/dist/types/getBuiltUnmergedDictionariesPath.d.ts.map +1 -0
  106. package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts +2 -0
  107. package/dist/types/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.d.ts.map +1 -0
  108. package/dist/types/index.d.ts +12 -7
  109. package/dist/types/index.d.ts.map +1 -1
  110. package/dist/types/listGitFiles.d.ts +9 -0
  111. package/dist/types/listGitFiles.d.ts.map +1 -0
  112. package/dist/types/loadDictionaries/loadDictionaries.d.ts.map +1 -1
  113. package/dist/types/loadDictionaries/loadDistantDictionaries.d.ts.map +1 -1
  114. package/dist/types/mergeDictionaries.d.ts +2 -4
  115. package/dist/types/mergeDictionaries.d.ts.map +1 -1
  116. package/dist/types/processPerLocaleDictionary.d.ts +32 -0
  117. package/dist/types/processPerLocaleDictionary.d.ts.map +1 -0
  118. package/dist/types/reduceDictionaryContent/applyMask.d.ts +3 -0
  119. package/dist/types/reduceDictionaryContent/applyMask.d.ts.map +1 -0
  120. package/dist/types/reduceDictionaryContent/buildMask.d.ts +5 -0
  121. package/dist/types/reduceDictionaryContent/buildMask.d.ts.map +1 -0
  122. package/dist/types/reduceDictionaryContent/reduceDictionaryContent.d.ts +3 -0
  123. package/dist/types/reduceDictionaryContent/reduceDictionaryContent.d.ts.map +1 -0
  124. package/dist/types/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.d.ts +38 -0
  125. package/dist/types/transpiler/declaration_file_to_dictionary/intlayer_dictionary/writeDictionary.d.ts.map +1 -1
  126. package/dist/types/transpiler/dictionary_to_main/createDictionaryEntryPoint.d.ts.map +1 -1
  127. package/dist/types/writeContentDeclaration/formatCode.d.ts +2 -0
  128. package/dist/types/writeContentDeclaration/formatCode.d.ts.map +1 -0
  129. package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
  130. package/dist/types/writeContentDeclaration/writeJSFile.d.ts +9 -0
  131. package/dist/types/writeContentDeclaration/writeJSFile.d.ts.map +1 -0
  132. package/package.json +21 -13
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var writeJSFile_exports = {};
30
+ __export(writeJSFile_exports, {
31
+ writeJSFile: () => writeJSFile
32
+ });
33
+ module.exports = __toCommonJS(writeJSFile_exports);
34
+ var import_generator = __toESM(require("@babel/generator"));
35
+ var babelParser = __toESM(require("@babel/parser"));
36
+ var import_traverse = __toESM(require("@babel/traverse"));
37
+ var t = __toESM(require("@babel/types"));
38
+ var import_config = require("@intlayer/config");
39
+ var import_core = require("@intlayer/core");
40
+ var import_fs = require("fs");
41
+ var import_promises = require("fs/promises");
42
+ var import_path = require("path");
43
+ var import_getContentDeclarationFileTemplate = require('../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs');
44
+ var import_formatCode = require('./formatCode.cjs');
45
+ const writeJSFile = async (filePath, dictionary) => {
46
+ const {
47
+ key: dictionaryIdentifierKey,
48
+ content: updatesToApply,
49
+ locale,
50
+ autoFilled
51
+ } = dictionary;
52
+ const isPerLocaleDeclarationFile = typeof locale === "string";
53
+ if (!(0, import_fs.existsSync)(filePath)) {
54
+ const fileExtension = (0, import_path.extname)(filePath);
55
+ let format = "ts";
56
+ if (fileExtension === ".ts" || fileExtension === ".tsx") {
57
+ format = "ts";
58
+ } else if (fileExtension === ".cjs" || fileExtension === ".cjsx") {
59
+ format = "cjs";
60
+ } else {
61
+ format = "esm";
62
+ }
63
+ (0, import_config.appLogger)("File does not exist, creating it", {
64
+ isVerbose: true
65
+ });
66
+ const template = await (0, import_getContentDeclarationFileTemplate.getContentDeclarationFileTemplate)(
67
+ dictionaryIdentifierKey,
68
+ format,
69
+ { locale, autoFilled }
70
+ );
71
+ await (0, import_promises.writeFile)(filePath, template, "utf-8");
72
+ }
73
+ let sourceCode;
74
+ try {
75
+ sourceCode = await (0, import_promises.readFile)(filePath, "utf-8");
76
+ } catch (error) {
77
+ const err = error;
78
+ (0, import_config.appLogger)(`Failed to read file: ${filePath}`, {
79
+ level: "error"
80
+ });
81
+ throw new Error(`Failed to read file ${filePath}: ${err.message}`);
82
+ }
83
+ const ast = babelParser.parse(sourceCode, {
84
+ sourceType: "module",
85
+ plugins: ["typescript", "jsx"],
86
+ tokens: true
87
+ });
88
+ let dictionaryObjectPath = null;
89
+ let dictionaryIdentifier = null;
90
+ (0, import_traverse.default)(ast, {
91
+ ObjectExpression(path) {
92
+ if (dictionaryObjectPath) return;
93
+ const keyProp = path.node.properties.find((prop) => {
94
+ if (!t.isObjectProperty(prop)) return false;
95
+ if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))
96
+ return false;
97
+ const keyName = t.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
98
+ if (keyName !== "key" || !t.isStringLiteral(prop.value)) return false;
99
+ const propValue = prop.value.value;
100
+ return propValue === dictionaryIdentifierKey;
101
+ });
102
+ if (keyProp) {
103
+ dictionaryObjectPath = path;
104
+ path.stop();
105
+ }
106
+ }
107
+ });
108
+ if (!dictionaryObjectPath) {
109
+ (0, import_config.appLogger)(`Looking for variable declarations`, {
110
+ isVerbose: true
111
+ });
112
+ const candidateVars = [];
113
+ (0, import_traverse.default)(ast, {
114
+ VariableDeclarator(path) {
115
+ const { node } = path;
116
+ if (!t.isIdentifier(node.id)) return;
117
+ let objPath = null;
118
+ if (node.init && t.isObjectExpression(node.init)) {
119
+ objPath = path.get("init");
120
+ } else if (node.init && (t.isTSAsExpression(node.init) || t.isTSTypeAssertion(node.init)) && t.isObjectExpression(node.init.expression)) {
121
+ objPath = path.get("init.expression");
122
+ }
123
+ if (objPath) {
124
+ candidateVars.push({ id: node.id.name, path: objPath });
125
+ }
126
+ }
127
+ });
128
+ (0, import_config.appLogger)(`Found ${candidateVars.length} candidate variables`, {
129
+ isVerbose: true
130
+ });
131
+ for (const { id, path } of candidateVars) {
132
+ const keyProp = path.node.properties.find((prop) => {
133
+ if (!t.isObjectProperty(prop)) return false;
134
+ if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))
135
+ return false;
136
+ const keyName = t.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
137
+ return keyName === "key" && t.isStringLiteral(prop.value) && prop.value.value === dictionaryIdentifierKey;
138
+ });
139
+ if (keyProp) {
140
+ (0, import_config.appLogger)(`Found match in variable: ${id}`);
141
+ dictionaryObjectPath = path;
142
+ dictionaryIdentifier = id;
143
+ break;
144
+ }
145
+ }
146
+ if (!dictionaryObjectPath) {
147
+ (0, import_config.appLogger)("Could not find dictionary object. Dumping all objects:", {
148
+ isVerbose: true
149
+ });
150
+ (0, import_traverse.default)(ast, {
151
+ ObjectExpression(path) {
152
+ const props = path.node.properties.map((prop) => {
153
+ if (!t.isObjectProperty(prop)) return "non-object-property";
154
+ if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))
155
+ return "complex-key";
156
+ const keyName = t.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
157
+ let valueDesc = "unknown-value";
158
+ if (t.isStringLiteral(prop.value)) {
159
+ valueDesc = `"${prop.value.value}"`;
160
+ }
161
+ return `${keyName}: ${valueDesc}`;
162
+ }).join(", ");
163
+ (0, import_config.appLogger)(`Object: { ${props} }`);
164
+ }
165
+ });
166
+ }
167
+ }
168
+ if (!dictionaryObjectPath) {
169
+ throw new Error(
170
+ `Could not find dictionary object with key '${dictionaryIdentifierKey}' in ${filePath}`
171
+ );
172
+ }
173
+ const contentPropertyPath = dictionaryObjectPath.get("properties").find((propPath) => {
174
+ if (!propPath.isObjectProperty()) return false;
175
+ const propNode = propPath.node;
176
+ const keyName = t.isIdentifier(propNode.key) ? propNode.key.name : t.isStringLiteral(propNode.key) ? propNode.key.value : null;
177
+ return keyName === "content";
178
+ });
179
+ if (!contentPropertyPath || !contentPropertyPath.isObjectProperty() || !contentPropertyPath.get("value").isObjectExpression()) {
180
+ throw new Error(
181
+ `Could not find 'content' object property, or it's not an object, in dictionary in ${filePath}`
182
+ );
183
+ }
184
+ const contentObjectPath = contentPropertyPath.get(
185
+ "value"
186
+ );
187
+ for (const [entryKeyToUpdate, newEntryData] of Object.entries(
188
+ updatesToApply
189
+ )) {
190
+ const targetPropertyPath = contentObjectPath.get("properties").find((propPath) => {
191
+ if (!propPath.isObjectProperty()) return false;
192
+ const propNode = propPath.node;
193
+ const keyName = t.isIdentifier(propNode.key) ? propNode.key.name : t.isStringLiteral(propNode.key) ? propNode.key.value : null;
194
+ return keyName === entryKeyToUpdate;
195
+ });
196
+ if (!targetPropertyPath || !targetPropertyPath.isObjectProperty()) {
197
+ (0, import_config.appLogger)(
198
+ `Key '${entryKeyToUpdate}' not found in content object of ${filePath}. Adding the missing key.`,
199
+ {
200
+ level: "info",
201
+ isVerbose: true
202
+ }
203
+ );
204
+ let valueNode;
205
+ if (newEntryData?.nodeType === import_core.NodeType.Translation) {
206
+ const translationContent = newEntryData;
207
+ if (isPerLocaleDeclarationFile && typeof locale === "string" && translationContent?.[import_core.NodeType.Translation]?.[locale]) {
208
+ valueNode = t.stringLiteral(
209
+ String(translationContent[import_core.NodeType.Translation][locale])
210
+ );
211
+ } else {
212
+ const translationsObj = t.objectExpression(
213
+ Object.entries(translationContent?.[import_core.NodeType.Translation]).map(
214
+ ([langKey, langValue]) => {
215
+ const keyNode2 = t.isValidIdentifier(langKey) ? t.identifier(langKey) : t.stringLiteral(langKey);
216
+ return t.objectProperty(
217
+ keyNode2,
218
+ t.stringLiteral(String(langValue))
219
+ );
220
+ }
221
+ )
222
+ );
223
+ valueNode = t.callExpression(t.identifier("t"), [translationsObj]);
224
+ }
225
+ } else if (typeof newEntryData === "string") {
226
+ valueNode = t.stringLiteral(newEntryData);
227
+ } else {
228
+ (0, import_config.appLogger)(
229
+ `Unsupported data type for new key '${entryKeyToUpdate}'. Using empty string.`,
230
+ { level: "warn", isVerbose: true }
231
+ );
232
+ valueNode = t.stringLiteral("");
233
+ }
234
+ const keyNode = t.isValidIdentifier(entryKeyToUpdate) ? t.identifier(entryKeyToUpdate) : t.stringLiteral(entryKeyToUpdate);
235
+ const newProperty = t.objectProperty(keyNode, valueNode);
236
+ contentObjectPath.node.properties.push(newProperty);
237
+ continue;
238
+ }
239
+ const callExpressionPath = targetPropertyPath.get("value");
240
+ if (callExpressionPath.isCallExpression()) {
241
+ const calleeNode = callExpressionPath.node.callee;
242
+ const calleeName = t.isIdentifier(calleeNode) ? calleeNode.name : null;
243
+ if (newEntryData?.nodeType === "translation" && calleeName === "t") {
244
+ const args = callExpressionPath.node.arguments;
245
+ if (args.length === 0 || !t.isObjectExpression(args[0])) {
246
+ (0, import_config.appLogger)(
247
+ `'t' call for '${entryKeyToUpdate}' in ${filePath} does not have an object literal as its first argument. Skipping.`,
248
+ {
249
+ level: "warn",
250
+ isVerbose: true
251
+ }
252
+ );
253
+ continue;
254
+ }
255
+ if (isPerLocaleDeclarationFile && typeof locale === "string") {
256
+ const translations = newEntryData?.[import_core.NodeType.Translation];
257
+ if (translations[locale]) {
258
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(String(translations[locale])));
259
+ } else {
260
+ (0, import_config.appLogger)(
261
+ `Missing translation for locale '${locale}' in '${entryKeyToUpdate}'. Using first available translation.`,
262
+ { level: "warn", isVerbose: true }
263
+ );
264
+ const firstValue = Object.values(translations)[0];
265
+ if (firstValue) {
266
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(String(firstValue)));
267
+ }
268
+ }
269
+ continue;
270
+ }
271
+ const translationsObjectAstNode = args[0];
272
+ const processedLangKeysInJsonUpdate = /* @__PURE__ */ new Set();
273
+ translationsObjectAstNode.properties.forEach((prop) => {
274
+ if (t.isObjectProperty(prop)) {
275
+ const langKeyNode = prop.key;
276
+ const astLangKeyName = t.isIdentifier(langKeyNode) ? langKeyNode.name : t.isStringLiteral(langKeyNode) ? langKeyNode.value : null;
277
+ if (astLangKeyName && newEntryData?.[import_core.NodeType.Translation].hasOwnProperty(astLangKeyName)) {
278
+ prop.value = t.stringLiteral(
279
+ String(
280
+ newEntryData?.[import_core.NodeType.Translation]?.[astLangKeyName]
281
+ )
282
+ );
283
+ processedLangKeysInJsonUpdate.add(astLangKeyName);
284
+ }
285
+ }
286
+ });
287
+ for (const [jsonLangKey, jsonLangValue] of Object.entries(
288
+ newEntryData?.[import_core.NodeType.Translation]
289
+ )) {
290
+ if (!processedLangKeysInJsonUpdate.has(jsonLangKey)) {
291
+ const newKeyNode = t.isValidIdentifier(jsonLangKey) ? t.identifier(jsonLangKey) : t.stringLiteral(jsonLangKey);
292
+ translationsObjectAstNode.properties.push(
293
+ t.objectProperty(
294
+ newKeyNode,
295
+ t.stringLiteral(String(jsonLangValue))
296
+ )
297
+ );
298
+ }
299
+ }
300
+ } else {
301
+ (0, import_config.appLogger)(
302
+ `Unhandled callee '${calleeName || "unknown"}' for key '${entryKeyToUpdate}' in ${filePath}.`,
303
+ { level: "warn", isVerbose: true }
304
+ );
305
+ }
306
+ } else if (callExpressionPath.isStringLiteral()) {
307
+ if (typeof newEntryData === "string") {
308
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(newEntryData));
309
+ } else if (newEntryData?.[import_core.NodeType.Translation]) {
310
+ const translations = newEntryData[import_core.NodeType.Translation];
311
+ const firstValue = Object.values(translations)[0];
312
+ if (firstValue) {
313
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(String(firstValue)));
314
+ }
315
+ } else {
316
+ (0, import_config.appLogger)(
317
+ `Unhandled data structure for string replacement at '${entryKeyToUpdate}' in ${filePath}.`,
318
+ { level: "warn", isVerbose: true }
319
+ );
320
+ }
321
+ } else {
322
+ const valueType = callExpressionPath.node.type;
323
+ (0, import_config.appLogger)(
324
+ `Updating value of type ${valueType} for '${entryKeyToUpdate}' in ${filePath}`,
325
+ { level: "info", isVerbose: true }
326
+ );
327
+ if (typeof newEntryData === "string") {
328
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(newEntryData));
329
+ } else if (newEntryData?.[import_core.NodeType.Translation]) {
330
+ const translations = newEntryData[import_core.NodeType.Translation];
331
+ const localeMatch = filePath.match(/\.([a-z]{2})\.content\.(ts|js)$/i);
332
+ const locale2 = localeMatch ? localeMatch[1] : Object.keys(translations)[0];
333
+ if (translations[locale2]) {
334
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(String(translations[locale2])));
335
+ } else {
336
+ const firstValue = Object.values(translations)[0];
337
+ if (firstValue) {
338
+ targetPropertyPath.get("value").replaceWith(t.stringLiteral(String(firstValue)));
339
+ }
340
+ }
341
+ } else {
342
+ (0, import_config.appLogger)(
343
+ `Cannot update value of type ${valueType} for '${entryKeyToUpdate}' in ${filePath}. Unsupported data structure.`,
344
+ { level: "warn", isVerbose: true }
345
+ );
346
+ }
347
+ }
348
+ }
349
+ const generatedCode = (0, import_generator.default)(ast, {
350
+ retainLines: true,
351
+ comments: true,
352
+ jsescOption: {
353
+ minimal: true
354
+ // This ensures Unicode characters are not escaped
355
+ }
356
+ }).code;
357
+ let finalCode = generatedCode;
358
+ finalCode = await (0, import_formatCode.formatCode)(filePath, finalCode);
359
+ try {
360
+ await (0, import_promises.writeFile)(filePath, finalCode, "utf-8");
361
+ (0, import_config.logger)(`Successfully updated ${filePath}`, {
362
+ level: "info",
363
+ isVerbose: true
364
+ });
365
+ } catch (error) {
366
+ const err = error;
367
+ (0, import_config.logger)(`Failed to write updated file: ${filePath}`, {
368
+ level: "error"
369
+ });
370
+ throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);
371
+ }
372
+ };
373
+ // Annotate the CommonJS export names for ESM import in node:
374
+ 0 && (module.exports = {
375
+ writeJSFile
376
+ });
377
+ //# sourceMappingURL=writeJSFile.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import generator from '@babel/generator';\nimport * as babelParser from '@babel/parser';\nimport traverse, { NodePath } from '@babel/traverse';\nimport * as t from '@babel/types';\nimport { appLogger, logger } from '@intlayer/config';\nimport {\n Dictionary,\n NodeType,\n TranslationContent,\n TypedNode,\n} from '@intlayer/core';\nimport { existsSync } from 'fs';\nimport { readFile, writeFile } from 'fs/promises';\nimport { extname } from 'path';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport { formatCode } from './formatCode';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary\n): Promise<void> => {\n const {\n key: dictionaryIdentifierKey,\n content: updatesToApply,\n locale,\n autoFilled,\n } = dictionary;\n const isPerLocaleDeclarationFile = typeof locale === 'string';\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath);\n\n let format = 'ts' as 'ts' | 'cjs' | 'esm';\n\n if (fileExtension === '.ts' || fileExtension === '.tsx') {\n format = 'ts';\n } else if (fileExtension === '.cjs' || fileExtension === '.cjsx') {\n format = 'cjs';\n } else {\n format = 'esm';\n }\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n dictionaryIdentifierKey,\n format,\n { locale, autoFilled }\n );\n\n await writeFile(filePath, template, 'utf-8');\n }\n\n let sourceCode: string;\n try {\n sourceCode = await readFile(filePath, 'utf-8');\n } catch (error) {\n const err = error as Error;\n appLogger(`Failed to read file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to read file ${filePath}: ${err.message}`);\n }\n\n const ast = babelParser.parse(sourceCode, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n tokens: true,\n });\n\n let dictionaryObjectPath: NodePath<t.ObjectExpression> | null = null;\n let dictionaryIdentifier: string | null = null;\n\n // First look for direct objects with the right key, regardless of variable assignments\n traverse(ast, {\n ObjectExpression(path) {\n if (dictionaryObjectPath) return; // Already found\n\n // Check if this object has a key property with the right value\n const keyProp = path.node.properties.find((prop) => {\n if (!t.isObjectProperty(prop)) return false;\n if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))\n return false;\n\n const keyName = t.isIdentifier(prop.key)\n ? prop.key.name\n : prop.key.value;\n\n if (keyName !== 'key' || !t.isStringLiteral(prop.value)) return false;\n\n // Unescape the value for comparison\n const propValue = prop.value.value;\n // Compare actual string content, not just raw representation\n return propValue === dictionaryIdentifierKey;\n });\n\n if (keyProp) {\n dictionaryObjectPath = path;\n path.stop();\n }\n },\n });\n\n // If not found directly, look for variable declarations and exports\n if (!dictionaryObjectPath) {\n appLogger(`Looking for variable declarations`, {\n isVerbose: true,\n });\n\n // Collect all variable declarations with objects\n const candidateVars: { id: string; path: NodePath<t.ObjectExpression> }[] =\n [];\n\n traverse(ast, {\n VariableDeclarator(path) {\n const { node } = path;\n if (!t.isIdentifier(node.id)) return;\n\n let objPath: NodePath<t.ObjectExpression> | null = null;\n\n // Direct object assignment\n if (node.init && t.isObjectExpression(node.init)) {\n objPath = path.get('init') as NodePath<t.ObjectExpression>;\n }\n // Object with TS type assertion (satisfies/as)\n else if (\n node.init &&\n (t.isTSAsExpression(node.init) || t.isTSTypeAssertion(node.init)) &&\n t.isObjectExpression(node.init.expression)\n ) {\n objPath = path.get('init.expression') as NodePath<t.ObjectExpression>;\n }\n\n if (objPath) {\n candidateVars.push({ id: node.id.name, path: objPath });\n }\n },\n });\n\n appLogger(`Found ${candidateVars.length} candidate variables`, {\n isVerbose: true,\n });\n\n // Check each candidate for the key property\n for (const { id, path } of candidateVars) {\n const keyProp = path.node.properties.find((prop) => {\n if (!t.isObjectProperty(prop)) return false;\n if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))\n return false;\n\n const keyName = t.isIdentifier(prop.key)\n ? prop.key.name\n : prop.key.value;\n return (\n keyName === 'key' &&\n t.isStringLiteral(prop.value) &&\n prop.value.value === dictionaryIdentifierKey\n );\n });\n\n if (keyProp) {\n appLogger(`Found match in variable: ${id}`);\n dictionaryObjectPath = path;\n dictionaryIdentifier = id;\n break;\n }\n }\n\n // If still not found, dump all object expressions for debugging\n if (!dictionaryObjectPath) {\n appLogger('Could not find dictionary object. Dumping all objects:', {\n isVerbose: true,\n });\n traverse(ast, {\n ObjectExpression(path) {\n const props = path.node.properties\n .map((prop) => {\n if (!t.isObjectProperty(prop)) return 'non-object-property';\n if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key))\n return 'complex-key';\n\n const keyName = t.isIdentifier(prop.key)\n ? prop.key.name\n : prop.key.value;\n let valueDesc = 'unknown-value';\n\n if (t.isStringLiteral(prop.value)) {\n valueDesc = `\"${prop.value.value}\"`;\n }\n\n return `${keyName}: ${valueDesc}`;\n })\n .join(', ');\n\n appLogger(`Object: { ${props} }`);\n },\n });\n }\n }\n\n if (!dictionaryObjectPath) {\n throw new Error(\n `Could not find dictionary object with key '${dictionaryIdentifierKey}' in ${filePath}`\n );\n }\n\n // Find the 'content' property within the identified dictionary object\n const contentPropertyPath = (\n (dictionaryObjectPath as any).get('properties') as NodePath<\n t.ObjectProperty | t.SpreadElement | t.ObjectMethod\n >[]\n ).find((propPath) => {\n if (!propPath.isObjectProperty()) return false;\n const propNode = propPath.node;\n const keyName = t.isIdentifier(propNode.key)\n ? propNode.key.name\n : t.isStringLiteral(propNode.key)\n ? propNode.key.value\n : null;\n return keyName === 'content';\n });\n\n if (\n !contentPropertyPath ||\n !contentPropertyPath.isObjectProperty() ||\n !(contentPropertyPath.get('value') as NodePath).isObjectExpression()\n ) {\n throw new Error(\n `Could not find 'content' object property, or it's not an object, in dictionary in ${filePath}`\n );\n }\n\n const contentObjectPath = contentPropertyPath.get(\n 'value'\n ) as NodePath<t.ObjectExpression>;\n\n // Apply updates to each entry specified in the JSON\n for (const [entryKeyToUpdate, newEntryData] of Object.entries(\n updatesToApply\n )) {\n const targetPropertyPath = (\n contentObjectPath.get('properties') as NodePath<\n t.ObjectProperty | t.SpreadElement | t.ObjectMethod\n >[]\n ).find((propPath) => {\n if (!propPath.isObjectProperty()) return false;\n const propNode = propPath.node;\n const keyName = t.isIdentifier(propNode.key)\n ? propNode.key.name\n : t.isStringLiteral(propNode.key)\n ? propNode.key.value\n : null;\n return keyName === entryKeyToUpdate;\n });\n\n if (!targetPropertyPath || !targetPropertyPath.isObjectProperty()) {\n appLogger(\n `Key '${entryKeyToUpdate}' not found in content object of ${filePath}. Adding the missing key.`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n\n // Create a new property for the missing key\n let valueNode: t.Expression;\n\n if ((newEntryData as TypedNode)?.nodeType === NodeType.Translation) {\n // Create a new t() call with the translations\n const translationContent = newEntryData as TranslationContent;\n\n if (\n isPerLocaleDeclarationFile &&\n typeof locale === 'string' &&\n translationContent?.[NodeType.Translation]?.[locale]\n ) {\n // For per-locale files, use the string value directly\n valueNode = t.stringLiteral(\n String(translationContent[NodeType.Translation][locale])\n );\n } else {\n // Otherwise create a t() call with translations object\n const translationsObj = t.objectExpression(\n Object.entries(translationContent?.[NodeType.Translation]).map(\n ([langKey, langValue]) => {\n const keyNode = t.isValidIdentifier(langKey)\n ? t.identifier(langKey)\n : t.stringLiteral(langKey);\n return t.objectProperty(\n keyNode,\n t.stringLiteral(String(langValue))\n );\n }\n )\n );\n valueNode = t.callExpression(t.identifier('t'), [translationsObj]);\n }\n } else if (typeof newEntryData === 'string') {\n // Create a string literal for string values\n valueNode = t.stringLiteral(newEntryData);\n } else {\n // Fallback to empty string if we don't know how to handle this type\n appLogger(\n `Unsupported data type for new key '${entryKeyToUpdate}'. Using empty string.`,\n { level: 'warn', isVerbose: true }\n );\n valueNode = t.stringLiteral('');\n }\n\n // Add the new property to the content object\n const keyNode = t.isValidIdentifier(entryKeyToUpdate)\n ? t.identifier(entryKeyToUpdate)\n : t.stringLiteral(entryKeyToUpdate);\n const newProperty = t.objectProperty(keyNode, valueNode);\n contentObjectPath.node.properties.push(newProperty);\n\n continue;\n }\n\n const callExpressionPath = targetPropertyPath.get('value') as NodePath; // Path to the value, e.g., t(...)\n\n // Handle different types of values\n if (callExpressionPath.isCallExpression()) {\n const calleeNode = (callExpressionPath.node as t.CallExpression).callee;\n const calleeName = t.isIdentifier(calleeNode) ? calleeNode.name : null;\n\n // Handle 't' function calls\n if (\n (newEntryData as TypedNode)?.nodeType === 'translation' &&\n calleeName === 't'\n ) {\n const args = (callExpressionPath.node as t.CallExpression).arguments;\n if (args.length === 0 || !t.isObjectExpression(args[0])) {\n appLogger(\n `'t' call for '${entryKeyToUpdate}' in ${filePath} does not have an object literal as its first argument. Skipping.`,\n {\n level: 'warn',\n isVerbose: true,\n }\n );\n continue;\n }\n\n if (isPerLocaleDeclarationFile && typeof locale === 'string') {\n // For per-locale files, replace t() call with direct string\n const translations = (newEntryData as TranslationContent)?.[\n NodeType.Translation\n ];\n\n if (translations[locale]) {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(String(translations[locale])));\n } else {\n appLogger(\n `Missing translation for locale '${locale}' in '${entryKeyToUpdate}'. Using first available translation.`,\n { level: 'warn', isVerbose: true }\n );\n const firstValue = Object.values(translations)[0];\n if (firstValue) {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(String(firstValue)));\n }\n }\n continue;\n }\n\n const translationsObjectAstNode = args[0] as t.ObjectExpression;\n const processedLangKeysInJsonUpdate = new Set<string>();\n\n // Update existing language properties in the AST node\n translationsObjectAstNode.properties.forEach((prop: any) => {\n if (t.isObjectProperty(prop)) {\n const langKeyNode = prop.key;\n const astLangKeyName = t.isIdentifier(langKeyNode)\n ? langKeyNode.name\n : t.isStringLiteral(langKeyNode)\n ? langKeyNode.value\n : null;\n\n if (\n astLangKeyName &&\n (newEntryData as TranslationContent)?.[\n NodeType.Translation\n ].hasOwnProperty(astLangKeyName)\n ) {\n prop.value = t.stringLiteral(\n String(\n (newEntryData as TranslationContent)?.[\n NodeType.Translation\n ]?.[astLangKeyName]\n )\n );\n processedLangKeysInJsonUpdate.add(astLangKeyName);\n }\n }\n });\n\n // Add new language properties from the JSON update that were not originally in the AST node\n for (const [jsonLangKey, jsonLangValue] of Object.entries(\n (newEntryData as TranslationContent)?.[NodeType.Translation]\n )) {\n if (!processedLangKeysInJsonUpdate.has(jsonLangKey)) {\n const newKeyNode = t.isValidIdentifier(jsonLangKey)\n ? t.identifier(jsonLangKey)\n : t.stringLiteral(jsonLangKey);\n translationsObjectAstNode.properties.push(\n t.objectProperty(\n newKeyNode,\n t.stringLiteral(String(jsonLangValue))\n )\n );\n }\n }\n }\n // Handle other function calls in the future\n else {\n appLogger(\n `Unhandled callee '${calleeName || 'unknown'}' for key '${entryKeyToUpdate}' in ${filePath}.`,\n { level: 'warn', isVerbose: true }\n );\n }\n }\n // Handle direct string literals\n else if (callExpressionPath.isStringLiteral()) {\n // For string literals, directly replace with the new value\n if (typeof newEntryData === 'string') {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(newEntryData));\n } else if ((newEntryData as any)?.[NodeType.Translation]) {\n // Handle translation content (use first available translation)\n const translations = (newEntryData as TranslationContent)[\n NodeType.Translation\n ];\n const firstValue = Object.values(translations)[0];\n if (firstValue) {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(String(firstValue)));\n }\n } else {\n appLogger(\n `Unhandled data structure for string replacement at '${entryKeyToUpdate}' in ${filePath}.`,\n { level: 'warn', isVerbose: true }\n );\n }\n }\n // Handle other value types (objects, arrays, etc.)\n else {\n const valueType = callExpressionPath.node.type;\n appLogger(\n `Updating value of type ${valueType} for '${entryKeyToUpdate}' in ${filePath}`,\n { level: 'info', isVerbose: true }\n );\n\n // For simple values like strings, use direct replacement\n if (typeof newEntryData === 'string') {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(newEntryData));\n }\n // For translation content, use a smart approach\n else if ((newEntryData as any)?.[NodeType.Translation]) {\n // Extract just the value relevant to this file's locale\n const translations = (newEntryData as TranslationContent)[\n NodeType.Translation\n ];\n\n // Try to determine locale from file path (assuming a pattern like .fr.content.ts)\n const localeMatch = filePath.match(/\\.([a-z]{2})\\.content\\.(ts|js)$/i);\n const locale = localeMatch\n ? localeMatch[1]\n : Object.keys(translations)[0];\n\n if (translations[locale]) {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(String(translations[locale])));\n } else {\n // Fallback to first translation\n const firstValue = Object.values(translations)[0];\n if (firstValue) {\n targetPropertyPath\n .get('value')\n .replaceWith(t.stringLiteral(String(firstValue)));\n }\n }\n } else {\n appLogger(\n `Cannot update value of type ${valueType} for '${entryKeyToUpdate}' in ${filePath}. Unsupported data structure.`,\n { level: 'warn', isVerbose: true }\n );\n }\n }\n }\n\n // Generate JavaScript/TypeScript code from the modified AST\n const generatedCode = generator(ast, {\n retainLines: true,\n comments: true,\n jsescOption: {\n minimal: true, // This ensures Unicode characters are not escaped\n },\n }).code;\n\n let finalCode = generatedCode;\n\n finalCode = await formatCode(filePath, finalCode);\n\n // Write the modified code back to the file\n try {\n await writeFile(filePath, finalCode, 'utf-8');\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAsB;AACtB,kBAA6B;AAC7B,sBAAmC;AACnC,QAAmB;AACnB,oBAAkC;AAClC,kBAKO;AACP,gBAA2B;AAC3B,sBAAoC;AACpC,kBAAwB;AACxB,+CAAkD;AAClD,wBAA2B;AAQpB,MAAM,cAAc,OACzB,UACA,eACkB;AAClB,QAAM;AAAA,IACJ,KAAK;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF,IAAI;AACJ,QAAM,6BAA6B,OAAO,WAAW;AAGrD,MAAI,KAAC,sBAAW,QAAQ,GAAG;AACzB,UAAM,oBAAgB,qBAAQ,QAAQ;AAEtC,QAAI,SAAS;AAEb,QAAI,kBAAkB,SAAS,kBAAkB,QAAQ;AACvD,eAAS;AAAA,IACX,WAAW,kBAAkB,UAAU,kBAAkB,SAAS;AAChE,eAAS;AAAA,IACX,OAAO;AACL,eAAS;AAAA,IACX;AAEA,iCAAU,oCAAoC;AAAA,MAC5C,WAAW;AAAA,IACb,CAAC;AACD,UAAM,WAAW,UAAM;AAAA,MACrB;AAAA,MACA;AAAA,MACA,EAAE,QAAQ,WAAW;AAAA,IACvB;AAEA,cAAM,2BAAU,UAAU,UAAU,OAAO;AAAA,EAC7C;AAEA,MAAI;AACJ,MAAI;AACF,iBAAa,UAAM,0BAAS,UAAU,OAAO;AAA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BAAW,UAAU,SAAS;AAGhD,MAAI;AACF,cAAM,2BAAU,UAAU,WAAW,OAAO;AAC5C,8BAAO,wBAAwB,QAAQ,IAAI;AAAA,MACzC,OAAO;AAAA,MACP,WAAW;AAAA,IACb,CAAC;AAAA,EACH,SAAS,OAAO;AACd,UAAM,MAAM;AACZ,8BAAO,iCAAiC,QAAQ,IAAI;AAAA,MAClD,OAAO;AAAA,IACT,CAAC;AACD,UAAM,IAAI,MAAM,gCAAgC,QAAQ,KAAK,IAAI,OAAO,EAAE;AAAA,EAC5E;AACF;","names":["traverse","keyNode","locale","generator"]}
@@ -1,19 +1,19 @@
1
- import { basename, relative } from "path";
2
1
  import {
3
2
  appLogger,
4
3
  getConfiguration
5
4
  } from "@intlayer/config";
5
+ import { basename, relative } from "path";
6
6
  import { watch as chokidarWatch } from "chokidar";
7
7
  import { getBuiltDictionariesPath } from "../getBuiltDictionariesPath.mjs";
8
+ import { listDictionaries } from "../listDictionariesPath.mjs";
8
9
  import { loadLocalDictionaries } from "../loadDictionaries/loadLocalDictionaries.mjs";
10
+ import { prepareIntlayer } from "../prepareIntlayer.mjs";
9
11
  import { buildDictionary } from "../transpiler/declaration_file_to_dictionary/index.mjs";
10
12
  import { createDictionaryEntryPoint } from "../transpiler/dictionary_to_main/createDictionaryEntryPoint.mjs";
11
13
  import {
12
- createTypes,
13
- createModuleAugmentation
14
+ createModuleAugmentation,
15
+ createTypes
14
16
  } from "../transpiler/dictionary_to_type/index.mjs";
15
- import { prepareIntlayer } from "../prepareIntlayer.mjs";
16
- import { listDictionaries } from "../listDictionariesPath.mjs";
17
17
  const recentlyAddedFiles = /* @__PURE__ */ new Set();
18
18
  const handleAdditionalContentDeclarationFile = async (filePath, configuration) => {
19
19
  const { content } = configuration ?? getConfiguration({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/chokidar/watcher.ts"],"sourcesContent":["import { basename, relative } from 'path';\nimport {\n type IntlayerConfig,\n appLogger,\n getConfiguration,\n} from '@intlayer/config';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { getBuiltDictionariesPath } from '../getBuiltDictionariesPath';\nimport { loadLocalDictionaries } from '../loadDictionaries/loadLocalDictionaries';\nimport { buildDictionary } from '../transpiler/declaration_file_to_dictionary/index';\nimport { createDictionaryEntryPoint } from '../transpiler/dictionary_to_main/createDictionaryEntryPoint';\nimport {\n createTypes,\n createModuleAugmentation,\n} from '../transpiler/dictionary_to_type/index';\nimport { prepareIntlayer } from '../prepareIntlayer';\nimport { listDictionaries } from '../listDictionariesPath';\n\nconst recentlyAddedFiles = new Set<string>();\n\nexport const handleAdditionalContentDeclarationFile = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(\n `Additional file detected: ${relative(content.baseDir, filePath)}`,\n {\n isVerbose: true,\n }\n );\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n createTypes(dictionariesPaths);\n\n createDictionaryEntryPoint();\n\n appLogger('Dictionaries built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n};\n\nexport const handleUnlikedContentDeclarationFile = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(`Unlinked detected: ${relative(content.baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const files: string[] = listDictionaries(configuration);\n\n const localeDictionaries = await loadLocalDictionaries(files);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n createTypes(dictionariesPaths);\n\n createDictionaryEntryPoint();\n\n appLogger('Dictionaries rebuilt', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n};\n\nexport const handleContentDeclarationFileChange = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(`Change detected: ${relative(content.baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const updatedDictionariesPaths = await buildDictionary(localeDictionaries);\n const allDictionariesPaths: string[] = getBuiltDictionariesPath();\n\n createTypes(updatedDictionariesPaths);\n appLogger('TypeScript types built', {\n isVerbose: true,\n });\n\n if (\n updatedDictionariesPaths.some(\n (updatedDictionaryPath) =>\n !allDictionariesPaths.includes(updatedDictionaryPath)\n )\n ) {\n createDictionaryEntryPoint();\n\n appLogger('Dictionary list built', {\n isVerbose: true,\n });\n }\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configuration =\n options?.configuration ??\n getConfiguration({\n verbose: true,\n });\n\n const { watch: isWatchMode, watchedFilesPatternWithPath } =\n configuration.content;\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n recentlyAddedFiles.add(fileName);\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n\n setTimeout(() => recentlyAddedFiles.delete(fileName), 1000); // Allow time for unlink to trigger if it's a move\n })\n .on(\n 'change',\n async (filePath) =>\n await handleContentDeclarationFileChange(filePath, configuration)\n )\n .on('unlink', async (filePath) => {\n setTimeout(async () => {\n const fileName = basename(filePath);\n\n if (recentlyAddedFiles.has(fileName)) {\n // The file was moved, so ignore unlink\n return;\n }\n\n await handleUnlikedContentDeclarationFile(filePath, configuration);\n }, 300); // Allow time for unlink to trigger if it's a move\n })\n .on('error', async (error) => {\n appLogger('Watcher error: ' + error, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const configuration = options?.configuration ?? getConfiguration();\n\n await prepareIntlayer(configuration);\n\n if (configuration.content.watch || options.persistent) {\n // Start watching (assuming watch is also async)\n watch({ ...options, configuration });\n }\n};\n"],"mappings":"AAAA,SAAS,UAAU,gBAAgB;AACnC;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AAEP,SAA+B,SAAS,qBAAqB;AAC7D,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,uBAAuB;AAChC,SAAS,kCAAkC;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,MAAM,qBAAqB,oBAAI,IAAY;AAEpC,MAAM,yCAAyC,OACpD,UACA,kBACG;AACH,QAAM,EAAE,QAAQ,IACd,iBACA,iBAAiB;AAAA,IACf,SAAS;AAAA,EACX,CAAC;AAGH;AAAA,IACE,6BAA6B,SAAS,QAAQ,SAAS,QAAQ,CAAC;AAAA,IAChE;AAAA,MACE,WAAW;AAAA,IACb;AAAA,EACF;AAEA,QAAM,qBAAqB,MAAM,sBAAsB,QAAQ;AAE/D,QAAM,oBAAoB,MAAM,gBAAgB,kBAAkB;AAElE,cAAY,iBAAiB;AAE7B,6BAA2B;AAE3B,YAAU,sBAAsB;AAAA,IAC9B,WAAW;AAAA,EACb,CAAC;AAED,2BAAyB;AAEzB,YAAU,6BAA6B;AAAA,IACrC,WAAW;AAAA,EACb,CAAC;AACH;AAEO,MAAM,sCAAsC,OACjD,UACA,kBACG;AACH,QAAM,EAAE,QAAQ,IACd,iBACA,iBAAiB;AAAA,IACf,SAAS;AAAA,EACX,CAAC;AAGH,YAAU,sBAAsB,SAAS,QAAQ,SAAS,QAAQ,CAAC,IAAI;AAAA,IAC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I,QAAQ;AAE/B,UAAM,uCAAuC,UAAU,aAAa;AAEpE,eAAW,MAAM,mBAAmB,OAAO,QAAQ,GAAG,GAAI;AAAA,EAC5D,CAAC,EACA;AAAA,IACC;AAAA,IACA,OAAO,aACL,MAAM,mCAAmC,UAAU,aAAa;AAAA,EACpE,EACC,GAAG,UAAU,OAAO,aAAa;AAChC,eAAW,YAAY;AACrB,YAAM,WAAW,SAAS,QAAQ;AAElC,UAAI,mBAAmB,IAAI,QAAQ,GAAG;AAEpC;AAAA,MACF;AAEA,YAAM,oCAAoC,UAAU,aAAa;AAAA,IACnE,GAAG,GAAG;AAAA,EACR,CAAC,EACA,GAAG,SAAS,OAAO,UAAU;AAC5B,cAAU,oBAAoB,OAAO;AAAA,MACnC,OAAO;AAAA,IACT,CAAC;AAED,cAAU,oBAAoB;AAE9B,UAAM,gBAAgB,aAAa;AAAA,EACrC,CAAC;AACL;AAEO,MAAM,wBAAwB,OAAO,YAA2B;AACrE,QAAM,gBAAgB,SAAS,iBAAiB,iBAAiB;AAEjE,QAAM,gBAAgB,aAAa;AAEnC,MAAI,cAAc,QAAQ,SAAS,QAAQ,YAAY;AAErD,UAAM,EAAE,GAAG,SAAS,cAAc,CAAC;AAAA,EACrC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/chokidar/watcher.ts"],"sourcesContent":["import {\n type IntlayerConfig,\n appLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport { basename, relative } from 'path';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { getBuiltDictionariesPath } from '../getBuiltDictionariesPath';\nimport { listDictionaries } from '../listDictionariesPath';\nimport { loadLocalDictionaries } from '../loadDictionaries/loadLocalDictionaries';\nimport { prepareIntlayer } from '../prepareIntlayer';\nimport { buildDictionary } from '../transpiler/declaration_file_to_dictionary/index';\nimport { createDictionaryEntryPoint } from '../transpiler/dictionary_to_main/createDictionaryEntryPoint';\nimport {\n createModuleAugmentation,\n createTypes,\n} from '../transpiler/dictionary_to_type/index';\n\nconst recentlyAddedFiles = new Set<string>();\n\nexport const handleAdditionalContentDeclarationFile = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(\n `Additional file detected: ${relative(content.baseDir, filePath)}`,\n {\n isVerbose: true,\n }\n );\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n createTypes(dictionariesPaths);\n\n createDictionaryEntryPoint();\n\n appLogger('Dictionaries built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n};\n\nexport const handleUnlikedContentDeclarationFile = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(`Unlinked detected: ${relative(content.baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const files: string[] = listDictionaries(configuration);\n\n const localeDictionaries = await loadLocalDictionaries(files);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n createTypes(dictionariesPaths);\n\n createDictionaryEntryPoint();\n\n appLogger('Dictionaries rebuilt', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n};\n\nexport const handleContentDeclarationFileChange = async (\n filePath: string,\n configuration?: IntlayerConfig\n) => {\n const { content } =\n configuration ??\n getConfiguration({\n verbose: true,\n });\n\n // Process the file with the functionToRun\n appLogger(`Change detected: ${relative(content.baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const updatedDictionariesPaths = await buildDictionary(localeDictionaries);\n const allDictionariesPaths: string[] = getBuiltDictionariesPath();\n\n createTypes(updatedDictionariesPaths);\n appLogger('TypeScript types built', {\n isVerbose: true,\n });\n\n if (\n updatedDictionariesPaths.some(\n (updatedDictionaryPath) =>\n !allDictionariesPaths.includes(updatedDictionaryPath)\n )\n ) {\n createDictionaryEntryPoint();\n\n appLogger('Dictionary list built', {\n isVerbose: true,\n });\n }\n};\n\ntype WatchOptions = ChokidarOptions & {\n configuration?: IntlayerConfig;\n};\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: WatchOptions) => {\n const configuration =\n options?.configuration ??\n getConfiguration({\n verbose: true,\n });\n\n const { watch: isWatchMode, watchedFilesPatternWithPath } =\n configuration.content;\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('add', async (filePath) => {\n const fileName = basename(filePath);\n recentlyAddedFiles.add(fileName);\n\n await handleAdditionalContentDeclarationFile(filePath, configuration);\n\n setTimeout(() => recentlyAddedFiles.delete(fileName), 1000); // Allow time for unlink to trigger if it's a move\n })\n .on(\n 'change',\n async (filePath) =>\n await handleContentDeclarationFileChange(filePath, configuration)\n )\n .on('unlink', async (filePath) => {\n setTimeout(async () => {\n const fileName = basename(filePath);\n\n if (recentlyAddedFiles.has(fileName)) {\n // The file was moved, so ignore unlink\n return;\n }\n\n await handleUnlikedContentDeclarationFile(filePath, configuration);\n }, 300); // Allow time for unlink to trigger if it's a move\n })\n .on('error', async (error) => {\n appLogger('Watcher error: ' + error, {\n level: 'error',\n });\n\n appLogger('Restarting watcher');\n\n await prepareIntlayer(configuration);\n });\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const configuration = options?.configuration ?? getConfiguration();\n\n await prepareIntlayer(configuration);\n\n if (configuration.content.watch || options.persistent) {\n // Start watching (assuming watch is also async)\n watch({ ...options, configuration });\n }\n};\n"],"mappings":"AAAA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,UA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YAAM,oCAAoC,UAAU,aAAa;AAAA,IACnE,GAAG,GAAG;AAAA,EACR,CAAC,EACA,GAAG,SAAS,OAAO,UAAU;AAC5B,cAAU,oBAAoB,OAAO;AAAA,MACnC,OAAO;AAAA,IACT,CAAC;AAED,cAAU,oBAAoB;AAE9B,UAAM,gBAAgB,aAAa;AAAA,EACrC,CAAC;AACL;AAEO,MAAM,wBAAwB,OAAO,YAA2B;AACrE,QAAM,gBAAgB,SAAS,iBAAiB,iBAAiB;AAEjE,QAAM,gBAAgB,aAAa;AAEnC,MAAI,cAAc,QAAQ,SAAS,QAAQ,YAAY;AAErD,UAAM,EAAE,GAAG,SAAS,cAAc,CAAC;AAAA,EACrC;AACF;","names":[]}
@@ -1,15 +1,13 @@
1
- import { existsSync, rmSync } from "fs";
2
1
  import { getConfiguration } from "@intlayer/config";
2
+ import { existsSync, rmSync } from "fs";
3
3
  import { createDictionaryEntryPoint } from "./transpiler/dictionary_to_main/createDictionaryEntryPoint.mjs";
4
4
  const cleanOutputDir = (configuration = getConfiguration()) => {
5
- const { resultDir, typesDir, dictionariesDir } = configuration.content;
6
- if (existsSync(resultDir)) {
7
- if (existsSync(dictionariesDir)) {
8
- rmSync(dictionariesDir, { recursive: true });
9
- }
10
- if (existsSync(typesDir)) {
11
- rmSync(typesDir, { recursive: true });
12
- }
5
+ const { dictionariesDir, typesDir } = configuration.content;
6
+ if (existsSync(dictionariesDir)) {
7
+ rmSync(dictionariesDir, { recursive: true });
8
+ }
9
+ if (existsSync(typesDir)) {
10
+ rmSync(typesDir, { recursive: true });
13
11
  }
14
12
  createDictionaryEntryPoint(configuration);
15
13
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cleanOutputDir.ts"],"sourcesContent":["import { existsSync, rmSync } from 'fs';\nimport { getConfiguration } from '@intlayer/config';\nimport { createDictionaryEntryPoint } from './transpiler/dictionary_to_main/createDictionaryEntryPoint';\n\nexport const cleanOutputDir = (configuration = getConfiguration()) => {\n const { resultDir, typesDir, dictionariesDir } = configuration.content;\n\n if (existsSync(resultDir)) {\n // Delete the dictionary directory\n if (existsSync(dictionariesDir)) {\n rmSync(dictionariesDir, { recursive: true });\n }\n\n // Delete the types directory\n if (existsSync(typesDir)) {\n rmSync(typesDir, { recursive: true });\n }\n }\n\n createDictionaryEntryPoint(configuration);\n};\n"],"mappings":"AAAA,SAAS,YAAY,cAAc;AACnC,SAAS,wBAAwB;AACjC,SAAS,kCAAkC;AAEpC,MAAM,iBAAiB,CAAC,gBAAgB,iBAAiB,MAAM;AACpE,QAAM,EAAE,WAAW,UAAU,gBAAgB,IAAI,cAAc;AAE/D,MAAI,WAAW,SAAS,GAAG;AAEzB,QAAI,WAAW,eAAe,GAAG;AAC/B,aAAO,iBAAiB,EAAE,WAAW,KAAK,CAAC;AAAA,IAC7C;AAGA,QAAI,WAAW,QAAQ,GAAG;AACxB,aAAO,UAAU,EAAE,WAAW,KAAK,CAAC;AAAA,IACtC;AAAA,EACF;AAEA,6BAA2B,aAAa;AAC1C;","names":[]}
1
+ {"version":3,"sources":["../../src/cleanOutputDir.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config';\nimport { existsSync, rmSync } from 'fs';\nimport { createDictionaryEntryPoint } from './transpiler/dictionary_to_main/createDictionaryEntryPoint';\n\nexport const cleanOutputDir = (configuration = getConfiguration()) => {\n const { dictionariesDir, typesDir } = configuration.content;\n\n if (existsSync(dictionariesDir)) {\n // Delete the dictionary directory\n rmSync(dictionariesDir, { recursive: true });\n }\n\n // Delete the types directory\n if (existsSync(typesDir)) {\n rmSync(typesDir, { recursive: true });\n }\n\n createDictionaryEntryPoint(configuration);\n};\n"],"mappings":"AAAA,SAAS,wBAAwB;AACjC,SAAS,YAAY,cAAc;AACnC,SAAS,kCAAkC;AAEpC,MAAM,iBAAiB,CAAC,gBAAgB,iBAAiB,MAAM;AACpE,QAAM,EAAE,iBAAiB,SAAS,IAAI,cAAc;AAEpD,MAAI,WAAW,eAAe,GAAG;AAE/B,WAAO,iBAAiB,EAAE,WAAW,KAAK,CAAC;AAAA,EAC7C;AAGA,MAAI,WAAW,QAAQ,GAAG;AACxB,WAAO,UAAU,EAAE,WAAW,KAAK,CAAC;AAAA,EACtC;AAEA,6BAA2B,aAAa;AAC1C;","names":[]}
@@ -1,4 +1,4 @@
1
- import { getIntlayerAPI } from "@intlayer/api";
1
+ import { getAuthAPI, getDictionaryAPI } from "@intlayer/api";
2
2
  import { appLogger, getConfiguration } from "@intlayer/config";
3
3
  import pLimit from "p-limit";
4
4
  import { logger } from "./log.mjs";
@@ -6,13 +6,14 @@ const fetchDistantDictionaries = async (options) => {
6
6
  try {
7
7
  const config = getConfiguration();
8
8
  const { clientId, clientSecret } = config.editor;
9
- const intlayerAPI = getIntlayerAPI(void 0, config);
9
+ const authAPI = getAuthAPI(void 0, config);
10
+ const dictionaryAPI = getDictionaryAPI(void 0, config);
10
11
  if (!clientId || !clientSecret) {
11
12
  throw new Error(
12
13
  "Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project."
13
14
  );
14
15
  }
15
- const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();
16
+ const oAuth2TokenResult = await authAPI.getOAuth2AccessToken();
16
17
  const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;
17
18
  const distantDictionariesKeys = options.dictionaryKeys;
18
19
  const limit = pLimit(5);
@@ -25,7 +26,7 @@ const fetchDistantDictionaries = async (options) => {
25
26
  }
26
27
  ]);
27
28
  try {
28
- const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(
29
+ const getDictionaryResult = await dictionaryAPI.getDictionary(
29
30
  dictionaryKey,
30
31
  void 0,
31
32
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["import { getIntlayerAPI } from '@intlayer/api';\n// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, getConfiguration } from '@intlayer/config';\nimport pLimit from 'p-limit';\nimport { logger } from './log';\n\ntype FetchDistantDictionariesOptions = {\n dictionaryKeys: string[];\n newDictionariesPath?: string;\n logPrefix?: string;\n};\n\n/**\n * Fetch distant dictionaries and update the logger with their statuses.\n */\nexport const fetchDistantDictionaries = async (\n options: FetchDistantDictionariesOptions\n): Promise<DictionaryAPI[]> => {\n try {\n const config = getConfiguration();\n const { clientId, clientSecret } = config.editor;\n const intlayerAPI = getIntlayerAPI(undefined, config);\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n const distantDictionariesKeys = options.dictionaryKeys;\n\n // Process dictionaries in parallel with a concurrency limit\n const limit = pLimit(5); // Limit the number of concurrent requests\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: { status: 'fetching' },\n },\n ]);\n\n try {\n // Fetch the dictionary\n const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(\n dictionaryKey,\n undefined,\n {\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n }\n );\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n logger.updateStatus([\n { dictionaryKey, type: 'distant', status: { status: 'imported' } },\n ]);\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n },\n },\n ]);\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(async () => await processDictionary(dictionaryKey))\n );\n\n const result = await Promise.all(fetchPromises);\n\n // Output any error messages\n const statuses = logger.getStatuses();\n for (const statusObj of statuses) {\n const currentState = statusObj.state.find((s) => s.type === 'distant');\n if (currentState && currentState.errorMessage) {\n appLogger(currentState.errorMessage, { level: 'error' });\n }\n }\n\n // Remove undefined values\n const filteredResult = result.filter(\n (dict): dict is DictionaryAPI => dict !== undefined\n );\n\n return filteredResult;\n } catch (error) {\n appLogger(error, { level: 'error' });\n return [];\n }\n};\n"],"mappings":"AAAA,SAAS,sBAAsB;AAG/B,SAAS,WAAW,wBAAwB;AAC5C,OAAO,YAAY;AACnB,SAAS,cAAc;AAWhB,MAAM,2BAA2B,OACtC,YAC6B;AAC7B,MAAI;AACF,UAAM,SAAS,iBAAiB;AAChC,UAAM,EAAE,UAAU,aAAa,IAAI,OAAO;AAC1C,UAAM,cAAc,eAAe,QAAW,MAAM;AAEpD,QAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,oBAAoB,MAAM,YAAY,KAAK,qBAAqB;AAEtE,UAAM,oBAAoB,kBAAkB,MAAM;AAElD,UAAM,0BAA0B,QAAQ;AAGxC,UAAM,QAAQ,OAAO,CAAC;AAEtB,UAAM,oBAAoB,OACxB,kBACuC;AACvC,aAAO,aAAa;AAAA,QAClB;AAAA,UACE;AAAA,UACA,MAAM;AAAA,UACN,QAAQ,EAAE,QAAQ,WAAW;AAAA,QAC/B;AAAA,MACF,CAAC;AAED,UAAI;AAEF,cAAM,sBAAsB,MAAM,YAAY,WAAW;AAAA,UACvD;AAAA,UACA;AAAA,UACA;AAAA,YACE,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,UAC1D;AAAA,QACF;AAEA,cAAM,oBAAoB,oBAAoB;AAE9C,YAAI,CAAC,mBAAmB;AACtB,gBAAM,IAAI,MAAM,cAAc,aAAa,sBAAsB;AAAA,QACnE;AAEA,eAAO,aAAa;AAAA,UAClB,EAAE,eAAe,MAAM,WAAW,QAAQ,EAAE,QAAQ,WAAW,EAAE;AAAA,QACnE,CAAC;AAED,eAAO;AAAA,MACT,SAAS,OAAO;AACd,eAAO,aAAa;AAAA,UAClB;AAAA,YACE;AAAA,YACA,MAAM;AAAA,YACN,QAAQ;AAAA,cACN,QAAQ;AAAA,cACR;AAAA,cACA,cAAc,GAAG,SAAS,aAAa,EAAE,6BAA6B,aAAa,KAAK,KAAK;AAAA,YAC/F;AAAA,UACF;AAAA,QACF,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,gBAAgB,wBAAwB;AAAA,MAAI,CAAC,kBACjD,MAAM,YAAY,MAAM,kBAAkB,aAAa,CAAC;AAAA,IAC1D;AAEA,UAAM,SAAS,MAAM,QAAQ,IAAI,aAAa;AAG9C,UAAM,WAAW,OAAO,YAAY;AACpC,eAAW,aAAa,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,kBAAU,aAAa,cAAc,EAAE,OAAO,QAAQ,CAAC;AAAA,MACzD;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,cAAU,OAAO,EAAE,OAAO,QAAQ,CAAC;AACnC,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["import { getAuthAPI, getDictionaryAPI } from '@intlayer/api';\n// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, getConfiguration } from '@intlayer/config';\nimport pLimit from 'p-limit';\nimport { logger } from './log';\n\ntype FetchDistantDictionariesOptions = {\n dictionaryKeys: string[];\n newDictionariesPath?: string;\n logPrefix?: string;\n};\n\n/**\n * Fetch distant dictionaries and update the logger with their statuses.\n */\nexport const fetchDistantDictionaries = async (\n options: FetchDistantDictionariesOptions\n): Promise<DictionaryAPI[]> => {\n try {\n const config = getConfiguration();\n const { clientId, clientSecret } = config.editor;\n const authAPI = getAuthAPI(undefined, config);\n const dictionaryAPI = getDictionaryAPI(undefined, config);\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await authAPI.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n const distantDictionariesKeys = options.dictionaryKeys;\n\n // Process dictionaries in parallel with a concurrency limit\n const limit = pLimit(5); // Limit the number of concurrent requests\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: { status: 'fetching' },\n },\n ]);\n\n try {\n // Fetch the dictionary\n const getDictionaryResult = await dictionaryAPI.getDictionary(\n dictionaryKey,\n undefined,\n {\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n }\n );\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n logger.updateStatus([\n { dictionaryKey, type: 'distant', status: { status: 'imported' } },\n ]);\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n },\n },\n ]);\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(async () => await processDictionary(dictionaryKey))\n );\n\n const result = await Promise.all(fetchPromises);\n\n // Output any error messages\n const statuses = logger.getStatuses();\n for (const statusObj of statuses) {\n const currentState = statusObj.state.find((s) => s.type === 'distant');\n if (currentState && currentState.errorMessage) {\n appLogger(currentState.errorMessage, { level: 'error' });\n }\n }\n\n // Remove undefined values\n const filteredResult = result.filter(\n (dict): dict is DictionaryAPI => dict !== undefined\n );\n\n return filteredResult;\n } catch (error) {\n appLogger(error, { level: 'error' });\n return [];\n }\n};\n"],"mappings":"AAAA,SAAS,YAAY,wBAAwB;AAG7C,SAAS,WAAW,wBAAwB;AAC5C,OAAO,YAAY;AACnB,SAAS,cAAc;AAWhB,MAAM,2BAA2B,OACtC,YAC6B;AAC7B,MAAI;AACF,UAAM,SAAS,iBAAiB;AAChC,UAAM,EAAE,UAAU,aAAa,IAAI,OAAO;AAC1C,UAAM,UAAU,WAAW,QAAW,MAAM;AAC5C,UAAM,gBAAgB,iBAAiB,QAAW,MAAM;AAExD,QAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,oBAAoB,MAAM,QAAQ,qBAAqB;AAE7D,UAAM,oBAAoB,kBAAkB,MAAM;AAElD,UAAM,0BAA0B,QAAQ;AAGxC,UAAM,QAAQ,OAAO,CAAC;AAEtB,UAAM,oBAAoB,OACxB,kBACuC;AACvC,aAAO,aAAa;AAAA,QAClB;AAAA,UACE;AAAA,UACA,MAAM;AAAA,UACN,QAAQ,EAAE,QAAQ,WAAW;AAAA,QAC/B;AAAA,MACF,CAAC;AAED,UAAI;AAEF,cAAM,sBAAsB,MAAM,cAAc;AAAA,UAC9C;AAAA,UACA;AAAA,UACA;AAAA,YACE,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,UAC1D;AAAA,QACF;AAEA,cAAM,oBAAoB,oBAAoB;AAE9C,YAAI,CAAC,mBAAmB;AACtB,gBAAM,IAAI,MAAM,cAAc,aAAa,sBAAsB;AAAA,QACnE;AAEA,eAAO,aAAa;AAAA,UAClB,EAAE,eAAe,MAAM,WAAW,QAAQ,EAAE,QAAQ,WAAW,EAAE;AAAA,QACnE,CAAC;AAED,eAAO;AAAA,MACT,SAAS,OAAO;AACd,eAAO,aAAa;AAAA,UAClB;AAAA,YACE;AAAA,YACA,MAAM;AAAA,YACN,QAAQ;AAAA,cACN,QAAQ;AAAA,cACR;AAAA,cACA,cAAc,GAAG,SAAS,aAAa,EAAE,6BAA6B,aAAa,KAAK,KAAK;AAAA,YAC/F;AAAA,UACF;AAAA,QACF,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,gBAAgB,wBAAwB;AAAA,MAAI,CAAC,kBACjD,MAAM,YAAY,MAAM,kBAAkB,aAAa,CAAC;AAAA,IAC1D;AAEA,UAAM,SAAS,MAAM,QAAQ,IAAI,aAAa;AAG9C,UAAM,WAAW,OAAO,YAAY;AACpC,eAAW,aAAa,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,kBAAU,aAAa,cAAc,EAAE,OAAO,QAAQ,CAAC;AAAA,MACzD;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,cAAU,OAAO,EAAE,OAAO,QAAQ,CAAC;AACnC,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
@@ -0,0 +1,37 @@
1
+ import {
2
+ deepTransformNode,
3
+ NodeType
4
+ } from "@intlayer/core";
5
+ const filterTranlationsPlugin = (locales) => ({
6
+ id: "filter-translations-plugin",
7
+ canHandle: (node) => typeof node === "object" && node?.nodeType === NodeType.Translation,
8
+ transform: (node, props, deepTransformNode2) => {
9
+ const translationMap = node.translation;
10
+ const filteredTranslationMap = Object.fromEntries(
11
+ Object.entries(translationMap).filter(
12
+ ([key]) => locales.includes(key)
13
+ )
14
+ );
15
+ return {
16
+ ...node,
17
+ translation: deepTransformNode2(filteredTranslationMap, {
18
+ ...props,
19
+ keyPath: [
20
+ ...props.keyPath,
21
+ { type: NodeType.Object, key: NodeType.Translation }
22
+ ]
23
+ })
24
+ };
25
+ }
26
+ });
27
+ const filterDictionaryLocales = (dictionary, locales) => {
28
+ return deepTransformNode(dictionary, {
29
+ plugins: [filterTranlationsPlugin(locales)],
30
+ dictionaryKey: dictionary.key,
31
+ keyPath: []
32
+ });
33
+ };
34
+ export {
35
+ filterDictionaryLocales
36
+ };
37
+ //# sourceMappingURL=filterDictionaryLocales.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/filterDictionaryLocales.ts"],"sourcesContent":["import type { Locales } from '@intlayer/config/client';\nimport {\n deepTransformNode,\n Dictionary,\n NodeType,\n Plugins,\n} from '@intlayer/core';\n\nconst filterTranlationsPlugin = (locales: Locales[]): Plugins => ({\n id: 'filter-translations-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Translation,\n transform: (node, props, deepTransformNode) => {\n const translationMap = node.translation as Record<Locales, string>;\n\n const filteredTranslationMap = Object.fromEntries(\n Object.entries(translationMap).filter(([key]) =>\n locales.includes(key as Locales)\n )\n );\n\n return {\n ...node,\n translation: deepTransformNode(filteredTranslationMap, {\n ...props,\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Object, key: NodeType.Translation },\n ],\n }),\n };\n },\n});\n\nexport const filterDictionaryLocales = (\n dictionary: Dictionary,\n locales: Locales[]\n) => {\n return deepTransformNode(dictionary, {\n plugins: [filterTranlationsPlugin(locales)],\n dictionaryKey: dictionary.key,\n keyPath: [],\n });\n};\n"],"mappings":"AACA;AAAA,EACE;AAAA,EAEA;AAAA,OAEK;AAEP,MAAM,0BAA0B,CAAC,aAAiC;AAAA,EAChE,IAAI;AAAA,EACJ,WAAW,CAAC,SACV,OAAO,SAAS,YAAY,MAAM,aAAa,SAAS;AAAA,EAC1D,WAAW,CAAC,MAAM,OAAOA,uBAAsB;AAC7C,UAAM,iBAAiB,KAAK;AAE5B,UAAM,yBAAyB,OAAO;AAAA,MACpC,OAAO,QAAQ,cAAc,EAAE;AAAA,QAAO,CAAC,CAAC,GAAG,MACzC,QAAQ,SAAS,GAAc;AAAA,MACjC;AAAA,IACF;AAEA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,aAAaA,mBAAkB,wBAAwB;AAAA,QACrD,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,MAAM;AAAA,UACT,EAAE,MAAM,SAAS,QAAQ,KAAK,SAAS,YAAY;AAAA,QACrD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,MAAM,0BAA0B,CACrC,YACA,YACG;AACH,SAAO,kBAAkB,YAAY;AAAA,IACnC,SAAS,CAAC,wBAAwB,OAAO,CAAC;AAAA,IAC1C,eAAe,WAAW;AAAA,IAC1B,SAAS,CAAC;AAAA,EACZ,CAAC;AACH;","names":["deepTransformNode"]}