gtx-cli 1.2.4 → 1.2.5-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/api/checkFileTranslations.js +107 -118
  2. package/dist/api/downloadFile.js +38 -47
  3. package/dist/api/downloadFileBatch.js +69 -77
  4. package/dist/api/fetchTranslations.js +17 -25
  5. package/dist/api/sendFiles.js +47 -56
  6. package/dist/api/sendUpdates.js +48 -45
  7. package/dist/api/waitForUpdates.js +15 -21
  8. package/dist/cli/base.js +133 -148
  9. package/dist/cli/react.js +149 -166
  10. package/dist/config/generateSettings.js +71 -83
  11. package/dist/config/validateSettings.js +1 -2
  12. package/dist/console/logging.d.ts +1 -1
  13. package/dist/console/logging.js +62 -115
  14. package/dist/formats/files/save.js +10 -21
  15. package/dist/formats/files/translate.js +127 -136
  16. package/dist/formats/gt/save.js +16 -27
  17. package/dist/fs/config/parseFilesConfig.js +6 -8
  18. package/dist/fs/config/setupConfig.js +32 -36
  19. package/dist/fs/config/updateConfig.js +27 -30
  20. package/dist/fs/determineFramework.js +4 -1
  21. package/dist/fs/findFilepath.js +1 -2
  22. package/dist/fs/index.d.ts +1 -0
  23. package/dist/fs/index.js +1 -0
  24. package/dist/fs/saveJSON.js +4 -15
  25. package/dist/hooks/postProcess.js +97 -107
  26. package/dist/next/config/parseNextConfig.js +44 -51
  27. package/dist/next/parse/handleInitGT.js +101 -112
  28. package/dist/next/parse/wrapContent.js +108 -112
  29. package/dist/react/config/createESBuildConfig.js +3 -12
  30. package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.js +11 -19
  31. package/dist/react/jsx/parse/parseStringFunction.js +3 -5
  32. package/dist/react/jsx/trimJsxStringChildren.js +5 -2
  33. package/dist/react/jsx/utils/parseAst.js +5 -6
  34. package/dist/react/jsx/utils/parseJsx.js +1 -1
  35. package/dist/react/jsx/utils/parseStringFunction.js +3 -5
  36. package/dist/react/parse/createDictionaryUpdates.js +58 -56
  37. package/dist/react/parse/createInlineUpdates.js +111 -118
  38. package/dist/react/parse/wrapContent.js +124 -128
  39. package/dist/react/utils/getVariableName.js +1 -2
  40. package/dist/setup/userInput.js +22 -33
  41. package/dist/setup/wizard.js +133 -134
  42. package/dist/translation/parse.js +52 -63
  43. package/dist/translation/stage.js +61 -68
  44. package/dist/translation/translate.js +13 -24
  45. package/dist/utils/credentials.js +75 -89
  46. package/dist/utils/installPackage.js +30 -41
  47. package/dist/utils/packageJson.js +49 -58
  48. package/dist/utils/packageManager.js +82 -54
  49. package/package.json +28 -11
  50. package/tsconfig.json +3 -3
package/dist/cli/react.js CHANGED
@@ -32,15 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
45
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
46
37
  };
@@ -99,11 +90,11 @@ class ReactCLI extends base_1.BaseCLI {
99
90
  .option('--ignore-errors', 'Ignore errors encountered while scanning for <T> tags', false)
100
91
  .option('--dry-run', 'Dry run, does not send updates to General Translation API', false)
101
92
  .option('--timeout <seconds>', 'Timeout in seconds for waiting for updates to be deployed to the CDN', DEFAULT_TIMEOUT.toString())
102
- .action((options) => __awaiter(this, void 0, void 0, function* () {
93
+ .action(async (options) => {
103
94
  (0, console_1.displayHeader)('Staging project for translation with approval...');
104
- yield this.handleStage(options);
95
+ await this.handleStage(options);
105
96
  (0, console_1.endCommand)('Done!');
106
- }));
97
+ });
107
98
  }
108
99
  setupTranslateCommand() {
109
100
  commander_1.program
@@ -122,11 +113,11 @@ class ReactCLI extends base_1.BaseCLI {
122
113
  .option('--ignore-errors', 'Ignore errors encountered while scanning for <T> tags', false)
123
114
  .option('--dry-run', 'Dry run, does not send updates to General Translation API', false)
124
115
  .option('--timeout <seconds>', 'Timeout in seconds for waiting for updates to be deployed to the CDN', DEFAULT_TIMEOUT.toString())
125
- .action((options) => __awaiter(this, void 0, void 0, function* () {
116
+ .action(async (options) => {
126
117
  (0, console_1.displayHeader)('Translating project...');
127
- yield this.handleTranslate(options);
118
+ await this.handleTranslate(options);
128
119
  (0, console_1.endCommand)('Done!');
129
- }));
120
+ });
130
121
  }
131
122
  setupGenerateSourceCommand() {
132
123
  commander_1.program
@@ -139,11 +130,11 @@ class ReactCLI extends base_1.BaseCLI {
139
130
  .option('--inline', 'Include inline <T> tags in addition to dictionary file', true)
140
131
  .option('--ignore-errors', 'Ignore errors encountered while scanning for <T> tags', false)
141
132
  .option('-t, --translations-dir, --translation-dir <path>', 'Path to directory where translations will be saved. If this flag is not provided, translations will not be saved locally.')
142
- .action((options) => __awaiter(this, void 0, void 0, function* () {
133
+ .action(async (options) => {
143
134
  (0, console_1.displayHeader)('Generating source templates...');
144
- yield this.handleGenerateSourceCommand(options);
135
+ await this.handleGenerateSourceCommand(options);
145
136
  (0, console_1.endCommand)('Done!');
146
- }));
137
+ });
147
138
  }
148
139
  setupScanCommand() {
149
140
  commander_1.program
@@ -153,169 +144,161 @@ class ReactCLI extends base_1.BaseCLI {
153
144
  .option('--config <path>', 'Filepath to config file, by default gt.config.json', (0, findFilepath_1.default)(['gt.config.json']))
154
145
  .option('--disable-ids', 'Disable id generation for the <T> tags', false)
155
146
  .option('--disable-formatting', 'Disable formatting of edited files', false)
156
- .action((options) => __awaiter(this, void 0, void 0, function* () {
147
+ .action(async (options) => {
157
148
  (0, console_1.displayHeader)('Scanning project...');
158
- yield this.handleScanCommand(options);
149
+ await this.handleScanCommand(options);
159
150
  (0, console_1.endCommand)('Done!');
160
- }));
151
+ });
161
152
  }
162
- handleGenerateSourceCommand(initOptions) {
163
- return __awaiter(this, void 0, void 0, function* () {
164
- const settings = yield (0, generateSettings_1.generateSettings)(initOptions);
165
- const options = Object.assign(Object.assign({}, initOptions), settings);
166
- if (!options.dictionary) {
167
- options.dictionary = (0, findFilepath_1.default)([
168
- './dictionary.js',
169
- './src/dictionary.js',
170
- './dictionary.json',
171
- './src/dictionary.json',
172
- './dictionary.ts',
173
- './src/dictionary.ts',
174
- ]);
153
+ async handleGenerateSourceCommand(initOptions) {
154
+ const settings = await (0, generateSettings_1.generateSettings)(initOptions);
155
+ const options = { ...initOptions, ...settings };
156
+ if (!options.dictionary) {
157
+ options.dictionary = (0, findFilepath_1.default)([
158
+ './dictionary.js',
159
+ './src/dictionary.js',
160
+ './dictionary.json',
161
+ './src/dictionary.json',
162
+ './dictionary.ts',
163
+ './src/dictionary.ts',
164
+ ]);
165
+ }
166
+ // User has to provide a dictionary file
167
+ // will not read from settings.files.resolvedPaths.json
168
+ const { updates, errors } = await (0, parse_1.createUpdates)(options, options.dictionary, this.library === 'gt-next' ? 'gt-next' : 'gt-react');
169
+ if (errors.length > 0) {
170
+ if (options.ignoreErrors) {
171
+ (0, console_1.logWarning)(chalk_1.default.red(`CLI tool encountered errors while scanning for ${chalk_1.default.green('<T>')} tags. These components will not be translated.\n` +
172
+ errors
173
+ .map((error) => chalk_1.default.yellow('• Warning: ') + error)
174
+ .join('\n')));
175
175
  }
176
- // User has to provide a dictionary file
177
- // will not read from settings.files.resolvedPaths.json
178
- const { updates, errors } = yield (0, parse_1.createUpdates)(options, options.dictionary, this.library === 'gt-next' ? 'gt-next' : 'gt-react');
179
- if (errors.length > 0) {
180
- if (options.ignoreErrors) {
181
- (0, console_1.logWarning)(chalk_1.default.red(`CLI tool encountered errors while scanning for ${chalk_1.default.green('<T>')} tags. These components will not be translated.\n` +
182
- errors
183
- .map((error) => chalk_1.default.yellow('• Warning: ') + error)
184
- .join('\n')));
185
- }
186
- else {
187
- (0, console_1.logError)(chalk_1.default.red(`CLI tool encountered errors while scanning for ${chalk_1.default.green('<T>')} tags. ${chalk_1.default.gray('To ignore these errors, re-run with --ignore-errors')}\n` +
188
- errors.map((error) => chalk_1.default.red('• Error: ') + error).join('\n')));
189
- }
176
+ else {
177
+ (0, console_1.logError)(chalk_1.default.red(`CLI tool encountered errors while scanning for ${chalk_1.default.green('<T>')} tags. ${chalk_1.default.gray('To ignore these errors, re-run with --ignore-errors')}\n` +
178
+ errors.map((error) => chalk_1.default.red(' Error: ') + error).join('\n')));
190
179
  }
191
- // Convert updates to the proper data format
192
- const newData = {};
193
- for (const update of updates) {
194
- const { source, metadata } = update;
195
- const { hash, id } = metadata;
196
- if (id) {
197
- newData[id] = source;
198
- }
199
- else {
200
- newData[hash] = source;
201
- }
180
+ }
181
+ // Convert updates to the proper data format
182
+ const newData = {};
183
+ for (const update of updates) {
184
+ const { source, metadata } = update;
185
+ const { hash, id } = metadata;
186
+ if (id) {
187
+ newData[id] = source;
202
188
  }
203
- // Save source file if files.json is provided
204
- if (settings.files && settings.files.placeholderPaths.gt) {
205
- const translationFiles = (0, parseFilesConfig_1.resolveLocaleFiles)(settings.files.placeholderPaths, settings.defaultLocale);
206
- if (!translationFiles.gt) {
207
- (0, console_1.logError)(errors_1.noFilesError);
208
- process.exit(1);
209
- }
210
- yield (0, saveJSON_1.saveJSON)(translationFiles.gt, newData);
211
- (0, console_1.logStep)('Source file saved successfully!');
212
- // Also save translations (after merging with existing translations)
213
- for (const locale of settings.locales) {
214
- const translationsFile = (0, parseFilesConfig_1.resolveLocaleFiles)(settings.files.placeholderPaths, locale);
215
- if (!translationsFile.gt) {
216
- continue;
217
- }
218
- const existingTranslations = (0, loadJSON_1.default)(translationsFile.gt);
219
- const mergedTranslations = Object.assign(Object.assign({}, newData), existingTranslations);
220
- // Filter out keys that don't exist in newData
221
- const filteredTranslations = Object.fromEntries(Object.entries(mergedTranslations).filter(([key]) => newData[key]));
222
- yield (0, saveJSON_1.saveJSON)(translationsFile.gt, filteredTranslations);
189
+ else {
190
+ newData[hash] = source;
191
+ }
192
+ }
193
+ // Save source file if files.json is provided
194
+ if (settings.files && settings.files.placeholderPaths.gt) {
195
+ const translationFiles = (0, parseFilesConfig_1.resolveLocaleFiles)(settings.files.placeholderPaths, settings.defaultLocale);
196
+ if (!translationFiles.gt) {
197
+ (0, console_1.logError)(errors_1.noFilesError);
198
+ process.exit(1);
199
+ }
200
+ await (0, saveJSON_1.saveJSON)(translationFiles.gt, newData);
201
+ (0, console_1.logStep)('Source file saved successfully!');
202
+ // Also save translations (after merging with existing translations)
203
+ for (const locale of settings.locales) {
204
+ const translationsFile = (0, parseFilesConfig_1.resolveLocaleFiles)(settings.files.placeholderPaths, locale);
205
+ if (!translationsFile.gt) {
206
+ continue;
223
207
  }
224
- (0, console_1.logStep)('Merged translations successfully!');
208
+ const existingTranslations = (0, loadJSON_1.default)(translationsFile.gt);
209
+ const mergedTranslations = {
210
+ ...newData,
211
+ ...existingTranslations,
212
+ };
213
+ // Filter out keys that don't exist in newData
214
+ const filteredTranslations = Object.fromEntries(Object.entries(mergedTranslations).filter(([key]) => newData[key]));
215
+ await (0, saveJSON_1.saveJSON)(translationsFile.gt, filteredTranslations);
225
216
  }
217
+ (0, console_1.logStep)('Merged translations successfully!');
218
+ }
219
+ }
220
+ async handleScanCommand(options) {
221
+ // Ask user for confirmation using inquirer
222
+ const answer = await (0, console_1.promptConfirm)({
223
+ message: chalk_1.default.yellow('Warning: This operation will modify your source files! Make sure you have committed or stashed your current changes. Do you want to continue?'),
224
+ defaultValue: true,
225
+ });
226
+ if (!answer) {
227
+ (0, console_1.logError)('Operation cancelled.');
228
+ process.exit(0);
229
+ }
230
+ // ----- Create a starter gt.config.json file -----
231
+ await (0, generateSettings_1.generateSettings)(options);
232
+ // ----- //
233
+ const includeTId = await (0, console_1.promptConfirm)({
234
+ message: 'Do you want to include an unique id for each <T> tag?',
235
+ defaultValue: true,
226
236
  });
237
+ options.disableIds = !includeTId;
238
+ let errors = [];
239
+ let warnings = [];
240
+ // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
241
+ const { filesUpdated } = await this.wrapContent(options, 'react', errors, warnings);
242
+ if (errors.length > 0) {
243
+ (0, console_1.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
244
+ }
245
+ // Format updated files if formatters are available
246
+ if (!options.disableFormatting)
247
+ await (0, postProcess_1.formatFiles)(filesUpdated);
248
+ (0, console_1.logSuccess)(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n` +
249
+ filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
250
+ if (filesUpdated.length > 0) {
251
+ (0, console_1.logStep)(chalk_1.default.green('Please verify the changes before committing.'));
252
+ }
253
+ if (warnings.length > 0) {
254
+ (0, console_1.logWarning)(chalk_1.default.yellow('Warnings encountered:') +
255
+ '\n' +
256
+ warnings
257
+ .map((warning) => `${chalk_1.default.yellow('-')} ${warning}`)
258
+ .join('\n'));
259
+ }
227
260
  }
228
- handleScanCommand(options) {
229
- return __awaiter(this, void 0, void 0, function* () {
230
- // Ask user for confirmation using inquirer
231
- const answer = yield (0, console_1.promptConfirm)({
232
- message: chalk_1.default.yellow('Warning: This operation will modify your source files! Make sure you have committed or stashed your current changes. Do you want to continue?'),
233
- defaultValue: true,
261
+ async handleStage(initOptions) {
262
+ const settings = await (0, generateSettings_1.generateSettings)(initOptions);
263
+ // First run the base class's handleTranslate method
264
+ const options = { ...initOptions, ...settings };
265
+ if (!settings.stageTranslations) {
266
+ // Update settings.stageTranslations to true
267
+ settings.stageTranslations = true;
268
+ await (0, updateConfig_1.default)({
269
+ configFilepath: options.config,
270
+ stageTranslations: true,
234
271
  });
235
- if (!answer) {
236
- (0, console_1.logError)('Operation cancelled.');
237
- process.exit(0);
238
- }
239
- // ----- Create a starter gt.config.json file -----
240
- yield (0, generateSettings_1.generateSettings)(options);
241
- // ----- //
242
- const includeTId = yield (0, console_1.promptConfirm)({
243
- message: 'Do you want to include an unique id for each <T> tag?',
244
- defaultValue: true,
245
- });
246
- options.disableIds = !includeTId;
247
- let errors = [];
248
- let warnings = [];
249
- // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
250
- const { filesUpdated } = yield this.wrapContent(options, 'react', errors, warnings);
251
- if (errors.length > 0) {
252
- (0, console_1.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
253
- }
254
- // Format updated files if formatters are available
255
- if (!options.disableFormatting)
256
- yield (0, postProcess_1.formatFiles)(filesUpdated);
257
- (0, console_1.logSuccess)(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n` +
258
- filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
259
- if (filesUpdated.length > 0) {
260
- (0, console_1.logStep)(chalk_1.default.green('Please verify the changes before committing.'));
261
- }
262
- if (warnings.length > 0) {
263
- (0, console_1.logWarning)(chalk_1.default.yellow('Warnings encountered:') +
264
- '\n' +
265
- warnings
266
- .map((warning) => `${chalk_1.default.yellow('-')} ${warning}`)
267
- .join('\n'));
268
- }
269
- });
272
+ }
273
+ const pkg = this.library === 'gt-next' ? 'gt-next' : 'gt-react';
274
+ await (0, stage_1.stageProject)(options, pkg);
270
275
  }
271
- handleStage(initOptions) {
272
- return __awaiter(this, void 0, void 0, function* () {
273
- const settings = yield (0, generateSettings_1.generateSettings)(initOptions);
274
- // First run the base class's handleTranslate method
275
- const options = Object.assign(Object.assign({}, initOptions), settings);
276
- if (!settings.stageTranslations) {
277
- // Update settings.stageTranslations to true
278
- settings.stageTranslations = true;
279
- yield (0, updateConfig_1.default)({
280
- configFilepath: options.config,
281
- stageTranslations: true,
282
- });
283
- }
276
+ async handleTranslate(initOptions) {
277
+ const settings = await (0, generateSettings_1.generateSettings)(initOptions);
278
+ // First run the base class's handleTranslate method
279
+ const options = { ...initOptions, ...settings };
280
+ try {
281
+ await super.handleGenericTranslate(options);
282
+ // If the base class's handleTranslate completes successfully, continue with ReactCLI-specific code
283
+ }
284
+ catch (error) {
285
+ // Continue with ReactCLI-specific code even if base handleTranslate failed
286
+ }
287
+ if (!settings.stageTranslations) {
288
+ // If stageTranslations is false, stage the project
284
289
  const pkg = this.library === 'gt-next' ? 'gt-next' : 'gt-react';
285
- yield (0, stage_1.stageProject)(options, pkg);
286
- });
287
- }
288
- handleTranslate(initOptions) {
289
- const _super = Object.create(null, {
290
- handleGenericTranslate: { get: () => super.handleGenericTranslate }
291
- });
292
- return __awaiter(this, void 0, void 0, function* () {
293
- const settings = yield (0, generateSettings_1.generateSettings)(initOptions);
294
- // First run the base class's handleTranslate method
295
- const options = Object.assign(Object.assign({}, initOptions), settings);
296
- try {
297
- yield _super.handleGenericTranslate.call(this, options);
298
- // If the base class's handleTranslate completes successfully, continue with ReactCLI-specific code
299
- }
300
- catch (error) {
301
- // Continue with ReactCLI-specific code even if base handleTranslate failed
302
- }
303
- if (!settings.stageTranslations) {
304
- // If stageTranslations is false, stage the project
305
- const pkg = this.library === 'gt-next' ? 'gt-next' : 'gt-react';
306
- const results = yield (0, stage_1.stageProject)(options, pkg);
307
- if (results) {
308
- yield (0, translate_1.translate)(options, results.versionId);
309
- }
290
+ const results = await (0, stage_1.stageProject)(options, pkg);
291
+ if (results) {
292
+ await (0, translate_1.translate)(options, results.versionId);
310
293
  }
311
- else {
312
- if (!settings._versionId) {
313
- (0, console_1.logError)(errors_1.noVersionIdError);
314
- process.exit(1);
315
- }
316
- yield (0, translate_1.translate)(options, settings._versionId);
294
+ }
295
+ else {
296
+ if (!settings._versionId) {
297
+ (0, console_1.logError)(errors_1.noVersionIdError);
298
+ process.exit(1);
317
299
  }
318
- });
300
+ await (0, translate_1.translate)(options, settings._versionId);
301
+ }
319
302
  }
320
303
  }
321
304
  exports.ReactCLI = ReactCLI;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -28,78 +19,75 @@ const constants_1 = require("../utils/constants");
28
19
  * @param options - The options to generate settings from
29
20
  * @returns The generated settings
30
21
  */
31
- function generateSettings(options) {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- var _a, _b;
34
- // Load config file
35
- let gtConfig = {};
36
- if (options.config && !options.config.endsWith('.json')) {
37
- options.config = `${options.config}.json`;
38
- }
39
- if (options.config) {
40
- gtConfig = (0, loadConfig_1.default)(options.config);
41
- }
42
- else if (node_fs_1.default.existsSync('gt.config.json')) {
43
- options.config = 'gt.config.json';
44
- gtConfig = (0, loadConfig_1.default)('gt.config.json');
45
- }
46
- else if (node_fs_1.default.existsSync('src/gt.config.json')) {
47
- options.config = 'src/gt.config.json';
48
- gtConfig = (0, loadConfig_1.default)('src/gt.config.json');
49
- }
50
- else {
51
- // If neither config exists, use empty config
52
- gtConfig = {};
53
- }
54
- // Warn if apiKey is present in gt.config.json
55
- if (gtConfig.apiKey) {
56
- (0, warnings_1.warnApiKeyInConfig)(options.config);
57
- process.exit(1);
58
- }
59
- // merge options
60
- const mergedOptions = Object.assign(Object.assign({}, gtConfig), options);
61
- // merge locales
62
- mergedOptions.locales = Array.from(new Set([...(gtConfig.locales || []), ...(options.locales || [])]));
63
- // Add apiKey if not provided
64
- mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;
65
- // Add projectId if not provided
66
- mergedOptions.projectId =
67
- mergedOptions.projectId || process.env.GT_PROJECT_ID;
68
- // Add baseUrl if not provided
69
- mergedOptions.baseUrl = mergedOptions.baseUrl || internal_1.defaultBaseUrl;
70
- // Add dashboardUrl if not provided
71
- mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || constants_1.GT_DASHBOARD_URL;
72
- // Add defaultLocale if not provided
73
- mergedOptions.defaultLocale =
74
- mergedOptions.defaultLocale || internal_1.libraryDefaultLocale;
75
- // Add locales if not provided
76
- mergedOptions.locales = mergedOptions.locales || [];
77
- // Add default config file name if not provided
78
- mergedOptions.config = mergedOptions.config || 'gt.config.json';
79
- // Display projectId if present
80
- if (mergedOptions.projectId)
81
- (0, console_1.displayProjectId)(mergedOptions.projectId);
82
- // Add stageTranslations if not provided
83
- // For human review, always stage the project
84
- mergedOptions.stageTranslations = (_a = mergedOptions.stageTranslations) !== null && _a !== void 0 ? _a : false;
85
- // Populate src if not provided
86
- mergedOptions.src =
87
- mergedOptions.src ||
88
- (0, findFilepath_1.findFilepaths)(['./src', './app', './pages', './components']);
89
- // Resolve all glob patterns in the files object
90
- mergedOptions.files = mergedOptions.files
91
- ? (0, parseFilesConfig_1.resolveFiles)(mergedOptions.files, mergedOptions.defaultLocale)
92
- : undefined;
93
- // if there's no existing config file, creates one
94
- // does not include the API key to avoid exposing it
95
- if (!node_fs_1.default.existsSync(mergedOptions.config)) {
96
- yield (0, setupConfig_1.default)(mergedOptions.config, {
97
- projectId: mergedOptions.projectId,
98
- defaultLocale: mergedOptions.defaultLocale,
99
- locales: ((_b = mergedOptions.locales) === null || _b === void 0 ? void 0 : _b.length) > 0 ? mergedOptions.locales : undefined,
100
- });
101
- }
102
- (0, validateSettings_1.validateSettings)(mergedOptions);
103
- return mergedOptions;
104
- });
22
+ async function generateSettings(options) {
23
+ // Load config file
24
+ let gtConfig = {};
25
+ if (options.config && !options.config.endsWith('.json')) {
26
+ options.config = `${options.config}.json`;
27
+ }
28
+ if (options.config) {
29
+ gtConfig = (0, loadConfig_1.default)(options.config);
30
+ }
31
+ else if (node_fs_1.default.existsSync('gt.config.json')) {
32
+ options.config = 'gt.config.json';
33
+ gtConfig = (0, loadConfig_1.default)('gt.config.json');
34
+ }
35
+ else if (node_fs_1.default.existsSync('src/gt.config.json')) {
36
+ options.config = 'src/gt.config.json';
37
+ gtConfig = (0, loadConfig_1.default)('src/gt.config.json');
38
+ }
39
+ else {
40
+ // If neither config exists, use empty config
41
+ gtConfig = {};
42
+ }
43
+ // Warn if apiKey is present in gt.config.json
44
+ if (gtConfig.apiKey) {
45
+ (0, warnings_1.warnApiKeyInConfig)(options.config);
46
+ process.exit(1);
47
+ }
48
+ // merge options
49
+ const mergedOptions = { ...gtConfig, ...options };
50
+ // merge locales
51
+ mergedOptions.locales = Array.from(new Set([...(gtConfig.locales || []), ...(options.locales || [])]));
52
+ // Add apiKey if not provided
53
+ mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;
54
+ // Add projectId if not provided
55
+ mergedOptions.projectId =
56
+ mergedOptions.projectId || process.env.GT_PROJECT_ID;
57
+ // Add baseUrl if not provided
58
+ mergedOptions.baseUrl = mergedOptions.baseUrl || internal_1.defaultBaseUrl;
59
+ // Add dashboardUrl if not provided
60
+ mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || constants_1.GT_DASHBOARD_URL;
61
+ // Add defaultLocale if not provided
62
+ mergedOptions.defaultLocale =
63
+ mergedOptions.defaultLocale || internal_1.libraryDefaultLocale;
64
+ // Add locales if not provided
65
+ mergedOptions.locales = mergedOptions.locales || [];
66
+ // Add default config file name if not provided
67
+ mergedOptions.config = mergedOptions.config || 'gt.config.json';
68
+ // Display projectId if present
69
+ if (mergedOptions.projectId)
70
+ (0, console_1.displayProjectId)(mergedOptions.projectId);
71
+ // Add stageTranslations if not provided
72
+ // For human review, always stage the project
73
+ mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;
74
+ // Populate src if not provided
75
+ mergedOptions.src =
76
+ mergedOptions.src ||
77
+ (0, findFilepath_1.findFilepaths)(['./src', './app', './pages', './components']);
78
+ // Resolve all glob patterns in the files object
79
+ mergedOptions.files = mergedOptions.files
80
+ ? (0, parseFilesConfig_1.resolveFiles)(mergedOptions.files, mergedOptions.defaultLocale)
81
+ : undefined;
82
+ // if there's no existing config file, creates one
83
+ // does not include the API key to avoid exposing it
84
+ if (!node_fs_1.default.existsSync(mergedOptions.config)) {
85
+ await (0, setupConfig_1.default)(mergedOptions.config, {
86
+ projectId: mergedOptions.projectId,
87
+ defaultLocale: mergedOptions.defaultLocale,
88
+ locales: mergedOptions.locales?.length > 0 ? mergedOptions.locales : undefined,
89
+ });
90
+ }
91
+ (0, validateSettings_1.validateSettings)(mergedOptions);
92
+ return mergedOptions;
105
93
  }
@@ -4,11 +4,10 @@ exports.validateSettings = validateSettings;
4
4
  const generaltranslation_1 = require("generaltranslation");
5
5
  const console_1 = require("../console");
6
6
  function validateSettings(settings) {
7
- var _a;
8
7
  // Validate locales
9
8
  for (const locale of settings.locales) {
10
9
  if (!(0, generaltranslation_1.isValidLocale)(locale)) {
11
- (0, console_1.logErrorAndExit)(`Provided locales: "${(_a = settings === null || settings === void 0 ? void 0 : settings.locales) === null || _a === void 0 ? void 0 : _a.join()}", ${locale} is not a valid locale!`);
10
+ (0, console_1.logErrorAndExit)(`Provided locales: "${settings?.locales?.join()}", ${locale} is not a valid locale!`);
12
11
  }
13
12
  }
14
13
  if (settings.defaultLocale && !(0, generaltranslation_1.isValidLocale)(settings.defaultLocale)) {
@@ -17,7 +17,7 @@ export declare function createSpinner(indicator?: 'dots' | 'timer'): {
17
17
  stop: (msg?: string, code?: number) => void;
18
18
  message: (msg?: string) => void;
19
19
  };
20
- export declare function createOraSpinner(indicator?: 'dots' | 'circleHalves'): Promise<import("ora").Ora>;
20
+ export declare function createOraSpinner(indicator?: 'dots' | 'circleHalves'): Promise<import("ora", { with: { "resolution-mode": "import" } }).Ora>;
21
21
  export declare function promptText({ message, defaultValue, validate, }: {
22
22
  message: string;
23
23
  defaultValue?: string;