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
@@ -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
  };
@@ -27,144 +18,152 @@ const wrapContent_1 = __importDefault(require("../react/parse/wrapContent"));
27
18
  const wrapContent_2 = __importDefault(require("../next/parse/wrapContent"));
28
19
  const packageManager_1 = require("../utils/packageManager");
29
20
  const installPackage_1 = require("../utils/installPackage");
30
- function handleSetupReactCommand(options) {
31
- return __awaiter(this, void 0, void 0, function* () {
32
- // Ask user for confirmation using inquirer
33
- const answer = yield (0, console_3.promptConfirm)({
34
- message: chalk_1.default.yellow(`This wizard will configure your React project for internationalization with GT.
21
+ async function handleSetupReactCommand(options) {
22
+ // Ask user for confirmation using inquirer
23
+ const answer = await (0, console_3.promptConfirm)({
24
+ message: chalk_1.default.yellow(`This wizard will configure your React project for internationalization with GT.
35
25
  If your project is already using a different i18n library, this wizard may cause issues.
36
26
 
37
27
  Make sure you have committed or stashed any changes. Do you want to continue?`),
28
+ defaultValue: true,
29
+ cancelMessage: 'Operation cancelled. You can re-run this wizard with: npx gtx-cli setup',
30
+ });
31
+ if (!answer) {
32
+ (0, console_2.logInfo)('Operation cancelled. You can re-run this wizard with: npx gtx-cli setup');
33
+ process.exit(0);
34
+ }
35
+ const frameworkType = await (0, console_1.promptSelect)({
36
+ message: 'What framework are you using?',
37
+ options: [
38
+ { value: 'next-app', label: chalk_1.default.blue('Next.js App Router') },
39
+ { value: 'next-pages', label: chalk_1.default.green('Next.js Pages Router') },
40
+ { value: 'vite', label: chalk_1.default.cyan('Vite + React') },
41
+ { value: 'gatsby', label: chalk_1.default.magenta('Gatsby') },
42
+ { value: 'react', label: chalk_1.default.yellow('React') },
43
+ { value: 'redwood', label: chalk_1.default.red('RedwoodJS') },
44
+ { value: 'other', label: chalk_1.default.gray('Other') },
45
+ ],
46
+ defaultValue: 'next-app',
47
+ });
48
+ if (frameworkType === 'other') {
49
+ (0, console_2.logError)(`Sorry, other React frameworks are not currently supported.
50
+ Please let us know what you would like to see supported at https://github.com/generaltranslation/gt/issues`);
51
+ process.exit(0);
52
+ }
53
+ const packageJson = await (0, packageJson_1.getPackageJson)();
54
+ // Check if gt-next or gt-react is installed
55
+ if (frameworkType === 'next-app' &&
56
+ !(0, packageJson_1.isPackageInstalled)('gt-next', packageJson)) {
57
+ const packageManager = await (0, packageManager_1.getPackageManager)();
58
+ const spinner = (0, console_1.createSpinner)('timer');
59
+ spinner.start(`Installing gt-next with ${packageManager.name}...`);
60
+ await (0, installPackage_1.installPackage)('gt-next', packageManager);
61
+ spinner.stop(chalk_1.default.green('Automatically installed gt-next.'));
62
+ }
63
+ else if (['next-pages', 'react', 'redwood', 'vite', 'gatsby'].includes(frameworkType) &&
64
+ !(0, packageJson_1.isPackageInstalled)('gt-react', packageJson)) {
65
+ const packageManager = await (0, packageManager_1.getPackageManager)();
66
+ const spinner = (0, console_1.createSpinner)('timer');
67
+ spinner.start(`Installing gt-react with ${packageManager.name}...`);
68
+ await (0, installPackage_1.installPackage)('gt-react', packageManager);
69
+ spinner.stop(chalk_1.default.green('Automatically installed gt-react.'));
70
+ }
71
+ // ----- Create a starter gt.config.json file -----
72
+ await (0, generateSettings_1.generateSettings)(options);
73
+ let errors = [];
74
+ let warnings = [];
75
+ let filesUpdated = [];
76
+ if (frameworkType === 'next-app') {
77
+ // Check if they have a next.config.js file
78
+ const nextConfigPath = (0, findFilepath_1.default)([
79
+ './next.config.js',
80
+ './next.config.ts',
81
+ './next.config.mjs',
82
+ './next.config.mts',
83
+ ]);
84
+ if (!nextConfigPath) {
85
+ (0, console_2.logError)('No next.config.[js|ts|mjs|mts] file found.');
86
+ process.exit(1);
87
+ }
88
+ const addGTProvider = await (0, console_3.promptConfirm)({
89
+ message: 'Do you want the setup wizard to automatically add the GTProvider component?',
38
90
  defaultValue: true,
39
- cancelMessage: 'Operation cancelled. You can re-run this wizard with: npx gtx-cli setup',
40
91
  });
41
- if (!answer) {
42
- (0, console_2.logInfo)('Operation cancelled. You can re-run this wizard with: npx gtx-cli setup');
43
- process.exit(0);
44
- }
45
- const frameworkType = yield (0, console_1.promptSelect)({
46
- message: 'What framework are you using?',
47
- options: [
48
- { value: 'next-app', label: chalk_1.default.blue('Next.js App Router') },
49
- { value: 'next-pages', label: chalk_1.default.green('Next.js Pages Router') },
50
- { value: 'vite', label: chalk_1.default.cyan('Vite + React') },
51
- { value: 'gatsby', label: chalk_1.default.magenta('Gatsby') },
52
- { value: 'react', label: chalk_1.default.yellow('React') },
53
- { value: 'redwood', label: chalk_1.default.red('RedwoodJS') },
54
- { value: 'other', label: chalk_1.default.gray('Other') },
55
- ],
56
- defaultValue: 'next-app',
92
+ const addWithGTConfig = await (0, console_3.promptConfirm)({
93
+ message: `Do you want to automatically add withGTConfig() to your ${nextConfigPath}?`,
94
+ defaultValue: true,
57
95
  });
58
- if (frameworkType === 'other') {
59
- (0, console_2.logError)(`Sorry, other React frameworks are not currently supported.
60
- Please let us know what you would like to see supported at https://github.com/generaltranslation/gt/issues`);
61
- process.exit(0);
62
- }
63
- const packageJson = yield (0, packageJson_1.getPackageJson)();
64
- // Check if gt-next or gt-react is installed
65
- if (frameworkType === 'next-app' &&
66
- !(0, packageJson_1.isPackageInstalled)('gt-next', packageJson)) {
67
- const packageManager = yield (0, packageManager_1.getPackageManager)();
68
- const spinner = (0, console_1.createSpinner)('timer');
69
- spinner.start(`Installing gt-next with ${packageManager.name}...`);
70
- yield (0, installPackage_1.installPackage)('gt-next', packageManager);
71
- spinner.stop(chalk_1.default.green('Automatically installed gt-next.'));
96
+ const includeTId = await (0, console_3.promptConfirm)({
97
+ message: 'Do you want to include an unique id for each <T> tag?',
98
+ defaultValue: true,
99
+ });
100
+ const mergeOptions = {
101
+ ...options,
102
+ disableIds: !includeTId,
103
+ disableFormatting: true,
104
+ addGTProvider,
105
+ };
106
+ const spinner = (0, console_1.createSpinner)();
107
+ spinner.start('Wrapping JSX content with <T> tags...');
108
+ // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
109
+ const { filesUpdated: filesUpdatedNext } = await (0, wrapContent_2.default)(mergeOptions, 'gt-next', errors, warnings);
110
+ filesUpdated = [...filesUpdated, ...filesUpdatedNext];
111
+ spinner.stop(chalk_1.default.green(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n`) + filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
112
+ if (addWithGTConfig) {
113
+ // Add the withGTConfig() function to the next.config.js file
114
+ await (0, handleInitGT_1.default)(nextConfigPath, errors, warnings, filesUpdated);
115
+ (0, console_2.logStep)(chalk_1.default.green(`Added withGTConfig() to your ${nextConfigPath} file.`));
72
116
  }
73
- else if (['next-pages', 'react', 'redwood', 'vite', 'gatsby'].includes(frameworkType) &&
74
- !(0, packageJson_1.isPackageInstalled)('gt-react', packageJson)) {
75
- const packageManager = yield (0, packageManager_1.getPackageManager)();
76
- const spinner = (0, console_1.createSpinner)('timer');
77
- spinner.start(`Installing gt-react with ${packageManager.name}...`);
78
- yield (0, installPackage_1.installPackage)('gt-react', packageManager);
79
- spinner.stop(chalk_1.default.green('Automatically installed gt-react.'));
117
+ if (errors.length > 0) {
118
+ (0, console_2.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
80
119
  }
81
- // ----- Create a starter gt.config.json file -----
82
- yield (0, generateSettings_1.generateSettings)(options);
83
- let errors = [];
84
- let warnings = [];
85
- let filesUpdated = [];
86
- if (frameworkType === 'next-app') {
87
- // Check if they have a next.config.js file
88
- const nextConfigPath = (0, findFilepath_1.default)([
89
- './next.config.js',
90
- './next.config.ts',
91
- './next.config.mjs',
92
- './next.config.mts',
93
- ]);
94
- if (!nextConfigPath) {
95
- (0, console_2.logError)('No next.config.[js|ts|mjs|mts] file found.');
96
- process.exit(1);
97
- }
98
- const addGTProvider = yield (0, console_3.promptConfirm)({
120
+ (0, console_2.logSuccess)(chalk_1.default.green(`Success! All JSX content has been wrapped with <T> tags${includeTId ? ' and unique ids.' : '.'}`));
121
+ (0, console_1.logMessage)(`To translate strings, see the docs on useGT and getGT: https://generaltranslation.com/docs/next/api/strings/getGT`);
122
+ }
123
+ else {
124
+ let addGTProvider = false;
125
+ if (frameworkType === 'next-pages') {
126
+ addGTProvider = await (0, console_3.promptConfirm)({
99
127
  message: 'Do you want the setup wizard to automatically add the GTProvider component?',
100
128
  defaultValue: true,
101
129
  });
102
- const addWithGTConfig = yield (0, console_3.promptConfirm)({
103
- message: `Do you want to automatically add withGTConfig() to your ${nextConfigPath}?`,
104
- defaultValue: true,
105
- });
106
- const includeTId = yield (0, console_3.promptConfirm)({
107
- message: 'Do you want to include an unique id for each <T> tag?',
108
- defaultValue: true,
109
- });
110
- const mergeOptions = Object.assign(Object.assign({}, options), { disableIds: !includeTId, disableFormatting: true, addGTProvider });
111
- const spinner = (0, console_1.createSpinner)();
112
- spinner.start('Wrapping JSX content with <T> tags...');
113
- // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
114
- const { filesUpdated: filesUpdatedNext } = yield (0, wrapContent_2.default)(mergeOptions, 'gt-next', errors, warnings);
115
- filesUpdated = [...filesUpdated, ...filesUpdatedNext];
116
- spinner.stop(chalk_1.default.green(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n`) + filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
117
- if (addWithGTConfig) {
118
- // Add the withGTConfig() function to the next.config.js file
119
- yield (0, handleInitGT_1.default)(nextConfigPath, errors, warnings, filesUpdated);
120
- (0, console_2.logStep)(chalk_1.default.green(`Added withGTConfig() to your ${nextConfigPath} file.`));
121
- }
122
- if (errors.length > 0) {
123
- (0, console_2.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
124
- }
125
- (0, console_2.logSuccess)(chalk_1.default.green(`Success! All JSX content has been wrapped with <T> tags${includeTId ? ' and unique ids.' : '.'}`));
126
- (0, console_1.logMessage)(`To translate strings, see the docs on useGT and getGT: https://generaltranslation.com/docs/next/api/strings/getGT`);
127
130
  }
128
- else {
129
- let addGTProvider = false;
130
- if (frameworkType === 'next-pages') {
131
- addGTProvider = yield (0, console_3.promptConfirm)({
132
- message: 'Do you want the setup wizard to automatically add the GTProvider component?',
133
- defaultValue: true,
134
- });
135
- }
136
- const includeTId = yield (0, console_3.promptConfirm)({
137
- message: 'Do you want to include an unique id for each <T> tag?',
138
- defaultValue: true,
139
- });
140
- const mergeOptions = Object.assign(Object.assign({}, options), { disableIds: !includeTId, disableFormatting: true, addGTProvider });
141
- const spinner = (0, console_1.createSpinner)();
142
- spinner.start('Wrapping JSX content with <T> tags...');
143
- // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
144
- const { filesUpdated: filesUpdatedReact } = yield (0, wrapContent_1.default)(mergeOptions, 'gt-react', frameworkType, errors, warnings);
145
- filesUpdated = [...filesUpdated, ...filesUpdatedReact];
146
- spinner.stop(chalk_1.default.green(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n`) + filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
147
- if (errors.length > 0) {
148
- (0, console_2.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
149
- }
150
- (0, console_2.logSuccess)(chalk_1.default.green(`Success! All JSX content has been wrapped with <T> tags${includeTId ? ' and unique ids.' : '.'}`));
151
- (0, console_1.logMessage)(`To translate strings, see the docs on useGT: https://generaltranslation.com/docs/react/api/strings/useGT`);
152
- }
153
- if (warnings.length > 0) {
154
- (0, console_2.logWarning)(chalk_1.default.yellow('Warnings encountered:') +
155
- '\n' +
156
- warnings.map((warning) => `${chalk_1.default.yellow('-')} ${warning}`).join('\n'));
157
- }
158
- const formatter = yield (0, postProcess_1.detectFormatter)();
159
- if (!formatter || filesUpdated.length === 0) {
160
- return;
161
- }
162
- const applyFormatting = yield (0, console_3.promptConfirm)({
163
- message: `Would you like the wizard to auto-format the modified files? ${chalk_1.default.gray(`(${formatter})`)}`,
131
+ const includeTId = await (0, console_3.promptConfirm)({
132
+ message: 'Do you want to include an unique id for each <T> tag?',
164
133
  defaultValue: true,
165
134
  });
166
- // Format updated files if formatters are available
167
- if (applyFormatting)
168
- yield (0, postProcess_2.formatFiles)(filesUpdated, formatter);
135
+ const mergeOptions = {
136
+ ...options,
137
+ disableIds: !includeTId,
138
+ disableFormatting: true,
139
+ addGTProvider,
140
+ };
141
+ const spinner = (0, console_1.createSpinner)();
142
+ spinner.start('Wrapping JSX content with <T> tags...');
143
+ // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
144
+ const { filesUpdated: filesUpdatedReact } = await (0, wrapContent_1.default)(mergeOptions, 'gt-react', frameworkType, errors, warnings);
145
+ filesUpdated = [...filesUpdated, ...filesUpdatedReact];
146
+ spinner.stop(chalk_1.default.green(`Success! Added <T> tags and updated ${chalk_1.default.bold.cyan(filesUpdated.length)} files:\n`) + filesUpdated.map((file) => `${chalk_1.default.green('-')} ${file}`).join('\n'));
147
+ if (errors.length > 0) {
148
+ (0, console_2.logError)(chalk_1.default.red('Failed to write files:\n') + errors.join('\n'));
149
+ }
150
+ (0, console_2.logSuccess)(chalk_1.default.green(`Success! All JSX content has been wrapped with <T> tags${includeTId ? ' and unique ids.' : '.'}`));
151
+ (0, console_1.logMessage)(`To translate strings, see the docs on useGT: https://generaltranslation.com/docs/react/api/strings/useGT`);
152
+ }
153
+ if (warnings.length > 0) {
154
+ (0, console_2.logWarning)(chalk_1.default.yellow('Warnings encountered:') +
155
+ '\n' +
156
+ warnings.map((warning) => `${chalk_1.default.yellow('-')} ${warning}`).join('\n'));
157
+ }
158
+ const formatter = await (0, postProcess_1.detectFormatter)();
159
+ if (!formatter || filesUpdated.length === 0) {
160
+ return;
161
+ }
162
+ const applyFormatting = await (0, console_3.promptConfirm)({
163
+ message: `Would you like the wizard to auto-format the modified files? ${chalk_1.default.gray(`(${formatter})`)}`,
164
+ defaultValue: true,
169
165
  });
166
+ // Format updated files if formatters are available
167
+ if (applyFormatting)
168
+ await (0, postProcess_2.formatFiles)(filesUpdated, formatter);
170
169
  }
@@ -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
  };
@@ -29,65 +20,63 @@ const chalk_1 = __importDefault(require("chalk"));
29
20
  * @param pkg - The package name
30
21
  * @returns An object containing the updates and errors
31
22
  */
32
- function createUpdates(options, sourceDictionary, pkg) {
33
- return __awaiter(this, void 0, void 0, function* () {
34
- let updates = [];
35
- let errors = [];
36
- // Parse dictionary with esbuildConfig
37
- if (sourceDictionary &&
38
- fs_1.default.existsSync(sourceDictionary) &&
39
- fs_1.default.statSync(sourceDictionary).isFile()) {
40
- if (sourceDictionary.endsWith('.json')) {
41
- updates = [
42
- ...updates,
43
- ...(yield (0, createDictionaryUpdates_1.default)(options, sourceDictionary)),
44
- ];
45
- }
46
- else {
47
- let esbuildConfig;
48
- if (options.jsconfig) {
49
- const jsconfig = (0, loadJSON_1.default)(options.jsconfig);
50
- if (!jsconfig) {
51
- (0, logging_1.logError)(`Failed to resolve jsconfig.json or tsconfig.json at provided filepath: "${options.jsconfig}"`);
52
- process.exit(1);
53
- }
54
- esbuildConfig = (0, createESBuildConfig_1.default)(jsconfig);
55
- }
56
- else {
57
- esbuildConfig = (0, createESBuildConfig_1.default)({});
58
- }
59
- updates = [
60
- ...updates,
61
- ...(yield (0, createDictionaryUpdates_1.default)(options, sourceDictionary, esbuildConfig)),
62
- ];
63
- }
64
- }
65
- // Scan through project for <T> tags
66
- if (options.inline) {
67
- const { updates: newUpdates, errors: newErrors } = yield (0, createInlineUpdates_1.default)(options, pkg);
68
- errors = [...errors, ...newErrors];
69
- updates = [...updates, ...newUpdates];
23
+ async function createUpdates(options, sourceDictionary, pkg) {
24
+ let updates = [];
25
+ let errors = [];
26
+ // Parse dictionary with esbuildConfig
27
+ if (sourceDictionary &&
28
+ fs_1.default.existsSync(sourceDictionary) &&
29
+ fs_1.default.statSync(sourceDictionary).isFile()) {
30
+ if (sourceDictionary.endsWith('.json')) {
31
+ updates = [
32
+ ...updates,
33
+ ...(await (0, createDictionaryUpdates_1.default)(options, sourceDictionary)),
34
+ ];
70
35
  }
71
- // Metadata addition and validation
72
- const idHashMap = new Map();
73
- const duplicateIds = new Set();
74
- updates = updates.map((update) => {
75
- if (!update.metadata.id)
76
- return update;
77
- const existingHash = idHashMap.get(update.metadata.id);
78
- if (existingHash) {
79
- if (existingHash !== update.metadata.hash) {
80
- errors.push(`Hashes don't match on two components with the same id: ${chalk_1.default.blue(update.metadata.id)}. Check your ${chalk_1.default.green('<T>')} tags and dictionary entries and make sure you're not accidentally duplicating IDs.`);
81
- duplicateIds.add(update.metadata.id);
36
+ else {
37
+ let esbuildConfig;
38
+ if (options.jsconfig) {
39
+ const jsconfig = (0, loadJSON_1.default)(options.jsconfig);
40
+ if (!jsconfig) {
41
+ (0, logging_1.logError)(`Failed to resolve jsconfig.json or tsconfig.json at provided filepath: "${options.jsconfig}"`);
42
+ process.exit(1);
82
43
  }
44
+ esbuildConfig = (0, createESBuildConfig_1.default)(jsconfig);
83
45
  }
84
46
  else {
85
- idHashMap.set(update.metadata.id, update.metadata.hash);
47
+ esbuildConfig = (0, createESBuildConfig_1.default)({});
86
48
  }
49
+ updates = [
50
+ ...updates,
51
+ ...(await (0, createDictionaryUpdates_1.default)(options, sourceDictionary, esbuildConfig)),
52
+ ];
53
+ }
54
+ }
55
+ // Scan through project for <T> tags
56
+ if (options.inline) {
57
+ const { updates: newUpdates, errors: newErrors } = await (0, createInlineUpdates_1.default)(options, pkg);
58
+ errors = [...errors, ...newErrors];
59
+ updates = [...updates, ...newUpdates];
60
+ }
61
+ // Metadata addition and validation
62
+ const idHashMap = new Map();
63
+ const duplicateIds = new Set();
64
+ updates = updates.map((update) => {
65
+ if (!update.metadata.id)
87
66
  return update;
88
- });
89
- // Filter out updates with duplicate IDs
90
- updates = updates.filter((update) => !duplicateIds.has(update.metadata.id));
91
- return { updates, errors };
67
+ const existingHash = idHashMap.get(update.metadata.id);
68
+ if (existingHash) {
69
+ if (existingHash !== update.metadata.hash) {
70
+ errors.push(`Hashes don't match on two components with the same id: ${chalk_1.default.blue(update.metadata.id)}. Check your ${chalk_1.default.green('<T>')} tags and dictionary entries and make sure you're not accidentally duplicating IDs.`);
71
+ duplicateIds.add(update.metadata.id);
72
+ }
73
+ }
74
+ else {
75
+ idHashMap.set(update.metadata.id, update.metadata.hash);
76
+ }
77
+ return update;
92
78
  });
79
+ // Filter out updates with duplicate IDs
80
+ updates = updates.filter((update) => !duplicateIds.has(update.metadata.id));
81
+ return { updates, errors };
93
82
  }
@@ -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
  };
@@ -20,65 +11,67 @@ const logging_1 = require("../console/logging");
20
11
  const parse_1 = require("./parse");
21
12
  const errors_2 = require("../console/errors");
22
13
  const sendUpdates_1 = require("../api/sendUpdates");
23
- function stageProject(settings, pkg) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- if (!settings.dictionary) {
26
- settings.dictionary = (0, findFilepath_1.default)([
27
- './dictionary.js',
28
- './src/dictionary.js',
29
- './dictionary.json',
30
- './src/dictionary.json',
31
- './dictionary.ts',
32
- './src/dictionary.ts',
33
- ]);
34
- }
35
- // Separate defaultLocale from locales
36
- settings.locales = settings.locales.filter((locale) => locale !== settings.defaultLocale);
37
- // validate timeout
38
- const timeout = parseInt(settings.timeout);
39
- if (isNaN(timeout) || timeout < 0) {
40
- (0, errors_1.logErrorAndExit)(`Invalid timeout: ${settings.timeout}. Must be a positive integer.`);
41
- }
42
- settings.timeout = timeout.toString();
43
- // ---- CREATING UPDATES ---- //
44
- const { updates, errors } = yield (0, parse_1.createUpdates)(settings, settings.dictionary, pkg);
45
- if (errors.length > 0) {
46
- if (settings.ignoreErrors) {
47
- (0, logging_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` +
48
- errors
49
- .map((error) => chalk_1.default.yellow('• Warning: ') + error + '\n')
50
- .join('')));
51
- }
52
- else {
53
- (0, logging_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` +
54
- errors
55
- .map((error) => chalk_1.default.red('• Error: ') + error + '\n')
56
- .join('')));
57
- }
58
- }
59
- if (settings.dryRun) {
60
- (0, logging_1.logSuccess)('Dry run: No translations were sent to General Translation.');
61
- return null;
62
- }
63
- if (updates.length == 0) {
64
- (0, logging_1.logError)(chalk_1.default.red(`No in-line content or dictionaries were found for ${chalk_1.default.green(pkg)}. Are you sure you're running this command in the right directory?`));
65
- return null;
66
- }
67
- // Send updates to General Translation API
68
- if (!settings.locales) {
69
- (0, errors_1.logErrorAndExit)(errors_2.noLocalesError);
70
- }
71
- if (!settings.defaultLocale) {
72
- (0, errors_1.logErrorAndExit)(errors_2.noDefaultLocaleError);
73
- }
74
- if (!settings.apiKey) {
75
- (0, errors_1.logErrorAndExit)(errors_2.noApiKeyError);
14
+ async function stageProject(settings, pkg) {
15
+ if (!settings.dictionary) {
16
+ settings.dictionary = (0, findFilepath_1.default)([
17
+ './dictionary.js',
18
+ './src/dictionary.js',
19
+ './dictionary.json',
20
+ './src/dictionary.json',
21
+ './dictionary.ts',
22
+ './src/dictionary.ts',
23
+ ]);
24
+ }
25
+ // Separate defaultLocale from locales
26
+ settings.locales = settings.locales.filter((locale) => locale !== settings.defaultLocale);
27
+ // validate timeout
28
+ const timeout = parseInt(settings.timeout);
29
+ if (isNaN(timeout) || timeout < 0) {
30
+ (0, errors_1.logErrorAndExit)(`Invalid timeout: ${settings.timeout}. Must be a positive integer.`);
31
+ }
32
+ settings.timeout = timeout.toString();
33
+ // ---- CREATING UPDATES ---- //
34
+ const { updates, errors } = await (0, parse_1.createUpdates)(settings, settings.dictionary, pkg);
35
+ if (errors.length > 0) {
36
+ if (settings.ignoreErrors) {
37
+ (0, logging_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` +
38
+ errors
39
+ .map((error) => chalk_1.default.yellow('• Warning: ') + error + '\n')
40
+ .join('')));
76
41
  }
77
- if (!settings.projectId) {
78
- (0, errors_1.logErrorAndExit)(errors_2.noProjectIdError);
42
+ else {
43
+ (0, logging_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` +
44
+ errors
45
+ .map((error) => chalk_1.default.red('• Error: ') + error + '\n')
46
+ .join('')));
79
47
  }
80
- const updateResponse = yield (0, sendUpdates_1.sendUpdates)(updates, Object.assign(Object.assign({}, settings), { timeout: settings.timeout, dataFormat: 'JSX' }), pkg);
81
- const { versionId, locales } = updateResponse;
82
- return { versionId, locales };
83
- });
48
+ }
49
+ if (settings.dryRun) {
50
+ (0, logging_1.logSuccess)('Dry run: No translations were sent to General Translation.');
51
+ return null;
52
+ }
53
+ if (updates.length == 0) {
54
+ (0, logging_1.logError)(chalk_1.default.red(`No in-line content or dictionaries were found for ${chalk_1.default.green(pkg)}. Are you sure you're running this command in the right directory?`));
55
+ return null;
56
+ }
57
+ // Send updates to General Translation API
58
+ if (!settings.locales) {
59
+ (0, errors_1.logErrorAndExit)(errors_2.noLocalesError);
60
+ }
61
+ if (!settings.defaultLocale) {
62
+ (0, errors_1.logErrorAndExit)(errors_2.noDefaultLocaleError);
63
+ }
64
+ if (!settings.apiKey) {
65
+ (0, errors_1.logErrorAndExit)(errors_2.noApiKeyError);
66
+ }
67
+ if (!settings.projectId) {
68
+ (0, errors_1.logErrorAndExit)(errors_2.noProjectIdError);
69
+ }
70
+ const updateResponse = await (0, sendUpdates_1.sendUpdates)(updates, {
71
+ ...settings,
72
+ timeout: settings.timeout,
73
+ dataFormat: 'JSX',
74
+ }, pkg);
75
+ const { versionId, locales } = updateResponse;
76
+ return { versionId, locales };
84
77
  }
@@ -1,31 +1,20 @@
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
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.translate = translate;
13
4
  const fetchTranslations_1 = require("../api/fetchTranslations");
14
5
  const waitForUpdates_1 = require("../api/waitForUpdates");
15
6
  const save_1 = require("../formats/gt/save");
16
- function translate(settings, versionId) {
17
- return __awaiter(this, void 0, void 0, function* () {
18
- // timeout was validated earlier
19
- const startTime = Date.now();
20
- const timeout = parseInt(settings.timeout) * 1000;
21
- const result = yield (0, waitForUpdates_1.waitForUpdates)(settings.apiKey, settings.baseUrl, versionId, startTime, timeout);
22
- if (!result) {
23
- process.exit(1);
24
- }
25
- const translations = yield (0, fetchTranslations_1.fetchTranslations)(settings.baseUrl, settings.apiKey, versionId);
26
- // Save translations to local directory if files.gt.output is provided
27
- if (settings.files && settings.files.placeholderPaths.gt) {
28
- yield (0, save_1.saveTranslations)(translations, settings.files.placeholderPaths, 'JSX');
29
- }
30
- });
7
+ async function translate(settings, versionId) {
8
+ // timeout was validated earlier
9
+ const startTime = Date.now();
10
+ const timeout = parseInt(settings.timeout) * 1000;
11
+ const result = await (0, waitForUpdates_1.waitForUpdates)(settings.apiKey, settings.baseUrl, versionId, startTime, timeout);
12
+ if (!result) {
13
+ process.exit(1);
14
+ }
15
+ const translations = await (0, fetchTranslations_1.fetchTranslations)(settings.baseUrl, settings.apiKey, versionId);
16
+ // Save translations to local directory if files.gt.output is provided
17
+ if (settings.files && settings.files.placeholderPaths.gt) {
18
+ await (0, save_1.saveTranslations)(translations, settings.files.placeholderPaths, 'JSX');
19
+ }
31
20
  }