gtx-cli 2.3.5 → 2.3.6-alpha.1

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 (191) hide show
  1. package/package.json +23 -18
  2. package/dist/api/checkFileTranslations.d.ts +0 -23
  3. package/dist/api/checkFileTranslations.js +0 -236
  4. package/dist/api/downloadFileBatch.d.ts +0 -20
  5. package/dist/api/downloadFileBatch.js +0 -113
  6. package/dist/api/sendFiles.d.ts +0 -17
  7. package/dist/api/sendFiles.js +0 -115
  8. package/dist/api/uploadFiles.d.ts +0 -27
  9. package/dist/api/uploadFiles.js +0 -40
  10. package/dist/cli/base.d.ts +0 -32
  11. package/dist/cli/base.js +0 -335
  12. package/dist/cli/commands/stage.d.ts +0 -5
  13. package/dist/cli/commands/stage.js +0 -100
  14. package/dist/cli/commands/translate.d.ts +0 -6
  15. package/dist/cli/commands/translate.js +0 -63
  16. package/dist/cli/flags.d.ts +0 -3
  17. package/dist/cli/flags.js +0 -38
  18. package/dist/cli/next.d.ts +0 -11
  19. package/dist/cli/next.js +0 -20
  20. package/dist/cli/react.d.ts +0 -18
  21. package/dist/cli/react.js +0 -175
  22. package/dist/config/generateSettings.d.ts +0 -9
  23. package/dist/config/generateSettings.js +0 -176
  24. package/dist/config/optionPresets.d.ts +0 -2
  25. package/dist/config/optionPresets.js +0 -56
  26. package/dist/config/resolveConfig.d.ts +0 -4
  27. package/dist/config/resolveConfig.js +0 -19
  28. package/dist/config/utils.d.ts +0 -2
  29. package/dist/config/utils.js +0 -4
  30. package/dist/config/validateSettings.d.ts +0 -3
  31. package/dist/config/validateSettings.js +0 -32
  32. package/dist/console/colors.d.ts +0 -5
  33. package/dist/console/colors.js +0 -16
  34. package/dist/console/index.d.ts +0 -21
  35. package/dist/console/index.js +0 -24
  36. package/dist/console/logging.d.ts +0 -53
  37. package/dist/console/logging.js +0 -185
  38. package/dist/formats/files/fileMapping.d.ts +0 -11
  39. package/dist/formats/files/fileMapping.js +0 -82
  40. package/dist/formats/files/save.d.ts +0 -5
  41. package/dist/formats/files/save.js +0 -17
  42. package/dist/formats/files/supportedFiles.d.ts +0 -10
  43. package/dist/formats/files/supportedFiles.js +0 -18
  44. package/dist/formats/files/translate.d.ts +0 -4
  45. package/dist/formats/files/translate.js +0 -119
  46. package/dist/formats/files/upload.d.ts +0 -13
  47. package/dist/formats/files/upload.js +0 -136
  48. package/dist/formats/gt/save.d.ts +0 -9
  49. package/dist/formats/gt/save.js +0 -26
  50. package/dist/formats/json/flattenJson.d.ts +0 -14
  51. package/dist/formats/json/flattenJson.js +0 -64
  52. package/dist/formats/json/mergeJson.d.ts +0 -13
  53. package/dist/formats/json/mergeJson.js +0 -257
  54. package/dist/formats/json/parseJson.d.ts +0 -2
  55. package/dist/formats/json/parseJson.js +0 -108
  56. package/dist/formats/json/utils.d.ts +0 -47
  57. package/dist/formats/json/utils.js +0 -149
  58. package/dist/formats/utils.d.ts +0 -2
  59. package/dist/formats/utils.js +0 -24
  60. package/dist/formats/yaml/mergeYaml.d.ts +0 -5
  61. package/dist/formats/yaml/mergeYaml.js +0 -55
  62. package/dist/formats/yaml/parseYaml.d.ts +0 -5
  63. package/dist/formats/yaml/parseYaml.js +0 -23
  64. package/dist/formats/yaml/utils.d.ts +0 -2
  65. package/dist/formats/yaml/utils.js +0 -22
  66. package/dist/fs/config/loadConfig.d.ts +0 -1
  67. package/dist/fs/config/loadConfig.js +0 -9
  68. package/dist/fs/config/parseFilesConfig.d.ts +0 -27
  69. package/dist/fs/config/parseFilesConfig.js +0 -129
  70. package/dist/fs/config/setupConfig.d.ts +0 -17
  71. package/dist/fs/config/setupConfig.js +0 -50
  72. package/dist/fs/config/updateConfig.d.ts +0 -10
  73. package/dist/fs/config/updateConfig.js +0 -36
  74. package/dist/fs/config/updateVersions.d.ts +0 -10
  75. package/dist/fs/config/updateVersions.js +0 -30
  76. package/dist/fs/copyFile.d.ts +0 -7
  77. package/dist/fs/copyFile.js +0 -39
  78. package/dist/fs/createLoadTranslationsFile.d.ts +0 -1
  79. package/dist/fs/createLoadTranslationsFile.js +0 -36
  80. package/dist/fs/determineFramework.d.ts +0 -5
  81. package/dist/fs/determineFramework.js +0 -46
  82. package/dist/fs/findFilepath.d.ts +0 -36
  83. package/dist/fs/findFilepath.js +0 -89
  84. package/dist/fs/getPackageResource.d.ts +0 -1
  85. package/dist/fs/getPackageResource.js +0 -6
  86. package/dist/fs/index.d.ts +0 -1
  87. package/dist/fs/index.js +0 -1
  88. package/dist/fs/loadJSON.d.ts +0 -6
  89. package/dist/fs/loadJSON.js +0 -17
  90. package/dist/fs/matchFiles.d.ts +0 -1
  91. package/dist/fs/matchFiles.js +0 -8
  92. package/dist/fs/saveJSON.d.ts +0 -1
  93. package/dist/fs/saveJSON.js +0 -7
  94. package/dist/fs/utils.d.ts +0 -1
  95. package/dist/fs/utils.js +0 -16
  96. package/dist/hooks/postProcess.d.ts +0 -4
  97. package/dist/hooks/postProcess.js +0 -110
  98. package/dist/index.d.ts +0 -4
  99. package/dist/index.js +0 -20
  100. package/dist/main.d.ts +0 -2
  101. package/dist/main.js +0 -9
  102. package/dist/next/config/parseNextConfig.d.ts +0 -10
  103. package/dist/next/config/parseNextConfig.js +0 -53
  104. package/dist/next/jsx/utils.d.ts +0 -7
  105. package/dist/next/jsx/utils.js +0 -42
  106. package/dist/next/parse/handleInitGT.d.ts +0 -7
  107. package/dist/next/parse/handleInitGT.js +0 -208
  108. package/dist/next/parse/wrapContent.d.ts +0 -11
  109. package/dist/next/parse/wrapContent.js +0 -163
  110. package/dist/react/config/createESBuildConfig.d.ts +0 -2
  111. package/dist/react/config/createESBuildConfig.js +0 -119
  112. package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.d.ts +0 -8
  113. package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.js +0 -111
  114. package/dist/react/jsx/evaluateJsx.d.ts +0 -17
  115. package/dist/react/jsx/evaluateJsx.js +0 -85
  116. package/dist/react/jsx/trimJsxStringChildren.d.ts +0 -7
  117. package/dist/react/jsx/trimJsxStringChildren.js +0 -95
  118. package/dist/react/jsx/utils/constants.d.ts +0 -10
  119. package/dist/react/jsx/utils/constants.js +0 -31
  120. package/dist/react/jsx/utils/parseAst.d.ts +0 -30
  121. package/dist/react/jsx/utils/parseAst.js +0 -277
  122. package/dist/react/jsx/utils/parseJsx.d.ts +0 -21
  123. package/dist/react/jsx/utils/parseJsx.js +0 -244
  124. package/dist/react/jsx/utils/parseStringFunction.d.ts +0 -16
  125. package/dist/react/jsx/utils/parseStringFunction.js +0 -411
  126. package/dist/react/jsx/utils/validateStringFunction.d.ts +0 -7
  127. package/dist/react/jsx/utils/validateStringFunction.js +0 -31
  128. package/dist/react/jsx/wrapJsx.d.ts +0 -51
  129. package/dist/react/jsx/wrapJsx.js +0 -387
  130. package/dist/react/parse/createDictionaryUpdates.d.ts +0 -3
  131. package/dist/react/parse/createDictionaryUpdates.js +0 -169
  132. package/dist/react/parse/createInlineUpdates.d.ts +0 -6
  133. package/dist/react/parse/createInlineUpdates.js +0 -122
  134. package/dist/react/parse/wrapContent.d.ts +0 -11
  135. package/dist/react/parse/wrapContent.js +0 -162
  136. package/dist/react/utils/flattenDictionary.d.ts +0 -20
  137. package/dist/react/utils/flattenDictionary.js +0 -75
  138. package/dist/react/utils/getEntryAndMetadata.d.ts +0 -5
  139. package/dist/react/utils/getEntryAndMetadata.js +0 -11
  140. package/dist/react/utils/getVariableName.d.ts +0 -25
  141. package/dist/react/utils/getVariableName.js +0 -37
  142. package/dist/setup/userInput.d.ts +0 -4
  143. package/dist/setup/userInput.js +0 -29
  144. package/dist/setup/wizard.d.ts +0 -2
  145. package/dist/setup/wizard.js +0 -127
  146. package/dist/translation/parse.d.ts +0 -15
  147. package/dist/translation/parse.js +0 -76
  148. package/dist/translation/stage.d.ts +0 -2
  149. package/dist/translation/stage.js +0 -44
  150. package/dist/translation/validate.d.ts +0 -2
  151. package/dist/translation/validate.js +0 -50
  152. package/dist/types/data/json.d.ts +0 -6
  153. package/dist/types/data/json.js +0 -1
  154. package/dist/types/data.d.ts +0 -30
  155. package/dist/types/data.js +0 -1
  156. package/dist/types/files.d.ts +0 -1
  157. package/dist/types/files.js +0 -1
  158. package/dist/types/index.d.ts +0 -173
  159. package/dist/types/index.js +0 -1
  160. package/dist/utils/addExplicitAnchorIds.d.ts +0 -24
  161. package/dist/utils/addExplicitAnchorIds.js +0 -260
  162. package/dist/utils/constants.d.ts +0 -2
  163. package/dist/utils/constants.js +0 -2
  164. package/dist/utils/credentials.d.ts +0 -12
  165. package/dist/utils/credentials.js +0 -119
  166. package/dist/utils/flattenJsonFiles.d.ts +0 -2
  167. package/dist/utils/flattenJsonFiles.js +0 -36
  168. package/dist/utils/gt.d.ts +0 -2
  169. package/dist/utils/gt.js +0 -2
  170. package/dist/utils/hash.d.ts +0 -6
  171. package/dist/utils/hash.js +0 -11
  172. package/dist/utils/headers.d.ts +0 -1
  173. package/dist/utils/headers.js +0 -14
  174. package/dist/utils/installPackage.d.ts +0 -3
  175. package/dist/utils/installPackage.js +0 -77
  176. package/dist/utils/localizeStaticImports.d.ts +0 -15
  177. package/dist/utils/localizeStaticImports.js +0 -341
  178. package/dist/utils/localizeStaticUrls.d.ts +0 -19
  179. package/dist/utils/localizeStaticUrls.js +0 -432
  180. package/dist/utils/packageInfo.d.ts +0 -3
  181. package/dist/utils/packageInfo.js +0 -17
  182. package/dist/utils/packageJson.d.ts +0 -6
  183. package/dist/utils/packageJson.js +0 -76
  184. package/dist/utils/packageManager.d.ts +0 -28
  185. package/dist/utils/packageManager.js +0 -269
  186. package/dist/utils/processAnchorIds.d.ts +0 -6
  187. package/dist/utils/processAnchorIds.js +0 -47
  188. package/dist/utils/sanitizeFileContent.d.ts +0 -6
  189. package/dist/utils/sanitizeFileContent.js +0 -29
  190. package/dist/utils/validateMdx.d.ts +0 -10
  191. package/dist/utils/validateMdx.js +0 -25
package/dist/cli/react.js DELETED
@@ -1,175 +0,0 @@
1
- import { displayHeader, endCommand, logError, logStep, logSuccess, logWarning, promptConfirm, } from '../console/logging.js';
2
- import loadJSON from '../fs/loadJSON.js';
3
- import findFilepath from '../fs/findFilepath.js';
4
- import chalk from 'chalk';
5
- import { formatFiles } from '../hooks/postProcess.js';
6
- import { BaseCLI } from './base.js';
7
- import { wrapContentReact } from '../react/parse/wrapContent.js';
8
- import { generateSettings } from '../config/generateSettings.js';
9
- import { saveJSON } from '../fs/saveJSON.js';
10
- import { resolveLocaleFiles } from '../fs/config/parseFilesConfig.js';
11
- import { noFilesError } from '../console/index.js';
12
- import { aggregateReactTranslations } from '../translation/stage.js';
13
- import { validateConfigExists } from '../config/validateSettings.js';
14
- import { validateProject } from '../translation/validate.js';
15
- import { intro } from '@clack/prompts';
16
- import { attachAdditionalReactTranslateFlags, attachTranslateFlags, } from './flags.js';
17
- const pkg = 'gt-react';
18
- export class ReactCLI extends BaseCLI {
19
- constructor(command, library, additionalModules) {
20
- super(command, library, additionalModules);
21
- }
22
- init() {
23
- this.setupStageCommand();
24
- this.setupTranslateCommand();
25
- this.setupGenerateSourceCommand();
26
- this.setupValidateCommand();
27
- }
28
- execute() {
29
- super.execute();
30
- }
31
- wrapContent(options, framework, errors, warnings) {
32
- return wrapContentReact(options, pkg, framework, errors, warnings);
33
- }
34
- setupStageCommand() {
35
- attachAdditionalReactTranslateFlags(attachTranslateFlags(this.program
36
- .command('stage')
37
- .description('Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'))).action(async (options) => {
38
- displayHeader('Staging project for translation with approval required...');
39
- await this.handleStage(options);
40
- endCommand('Done!');
41
- });
42
- }
43
- setupTranslateCommand() {
44
- attachAdditionalReactTranslateFlags(attachTranslateFlags(this.program
45
- .command('translate')
46
- .description('Scans the project for a dictionary and/or <T> tags, and sends the updates to the General Translation API for translation.'))).action(async (options) => {
47
- displayHeader('Translating project...');
48
- await this.handleTranslate(options);
49
- endCommand('Done!');
50
- });
51
- }
52
- setupValidateCommand() {
53
- this.program
54
- .command('validate [files...]')
55
- .description('Scans the project for a dictionary and/or <T> tags, and validates the project for errors.')
56
- .option('-c, --config <path>', 'Filepath to config file, by default gt.config.json', findFilepath(['gt.config.json']))
57
- .option('--tsconfig, --jsconfig <path>', 'Path to jsconfig or tsconfig file', findFilepath(['./tsconfig.json', './jsconfig.json']))
58
- .option('--dictionary <path>', 'Path to dictionary file')
59
- .option('--src <paths...>', "Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'")
60
- .option('--inline', 'Include inline <T> tags in addition to dictionary file', true)
61
- .action(async (files, options) => {
62
- // intro here since we don't want to show the ascii title
63
- intro(chalk.cyan('Validating project...'));
64
- await this.handleValidate(options, files);
65
- endCommand('Done!');
66
- });
67
- }
68
- setupGenerateSourceCommand() {
69
- attachAdditionalReactTranslateFlags(attachTranslateFlags(this.program
70
- .command('generate')
71
- .description('Generate a translation file for the source locale. This command should be used if you are handling your own translations.'))).action(async (initOptions) => {
72
- displayHeader('Generating source templates...');
73
- await this.handleGenerateSourceCommand(initOptions);
74
- endCommand('Done!');
75
- });
76
- }
77
- async handleGenerateSourceCommand(initOptions) {
78
- const settings = await generateSettings(initOptions);
79
- const updates = await aggregateReactTranslations(initOptions, settings, this.library === 'gt-next' ? 'gt-next' : 'gt-react');
80
- // Convert updates to the proper data format
81
- const newData = {};
82
- for (const update of updates) {
83
- const { source, metadata } = update;
84
- const { hash, id } = metadata;
85
- if (id) {
86
- newData[id] = source;
87
- }
88
- else {
89
- newData[hash] = source;
90
- }
91
- }
92
- // Save source file if files.json is provided
93
- if (settings.files && settings.files.placeholderPaths.gt) {
94
- const translationFiles = resolveLocaleFiles(settings.files.placeholderPaths, settings.defaultLocale);
95
- if (!translationFiles.gt) {
96
- logError(noFilesError);
97
- process.exit(1);
98
- }
99
- await saveJSON(translationFiles.gt, newData);
100
- logStep('Source file saved successfully!');
101
- // Also save translations (after merging with existing translations)
102
- for (const locale of settings.locales) {
103
- const translationsFile = resolveLocaleFiles(settings.files.placeholderPaths, locale);
104
- if (!translationsFile.gt) {
105
- continue;
106
- }
107
- const existingTranslations = loadJSON(translationsFile.gt);
108
- const mergedTranslations = {
109
- ...newData,
110
- ...existingTranslations,
111
- };
112
- // Filter out keys that don't exist in newData
113
- const filteredTranslations = Object.fromEntries(Object.entries(mergedTranslations).filter(([key]) => newData[key]));
114
- await saveJSON(translationsFile.gt, filteredTranslations);
115
- }
116
- logStep('Merged translations successfully!');
117
- }
118
- }
119
- async handleScanCommand(options) {
120
- // Ask user for confirmation using inquirer
121
- const answer = await promptConfirm({
122
- message: chalk.yellow('Warning: This operation will modify your source files! Make sure you have committed or stashed your current changes. Do you want to continue?'),
123
- defaultValue: true,
124
- });
125
- if (!answer) {
126
- logError('Operation cancelled.');
127
- process.exit(0);
128
- }
129
- // ----- Create a starter gt.config.json file -----
130
- await generateSettings(options);
131
- // ----- //
132
- const includeTId = await promptConfirm({
133
- message: 'Do you want to include an unique id for each <T> tag?',
134
- defaultValue: true,
135
- });
136
- options.disableIds = !includeTId;
137
- const errors = [];
138
- const warnings = [];
139
- // Wrap all JSX elements in the src directory with a <T> tag, with unique ids
140
- const { filesUpdated } = await this.wrapContent(options, 'react', errors, warnings);
141
- if (errors.length > 0) {
142
- logError(chalk.red('Failed to write files:\n') + errors.join('\n'));
143
- }
144
- // Format updated files if formatters are available
145
- if (!options.disableFormatting)
146
- await formatFiles(filesUpdated);
147
- logSuccess(`Success! Added <T> tags and updated ${chalk.bold.cyan(filesUpdated.length)} files:\n` +
148
- filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\n'));
149
- if (filesUpdated.length > 0) {
150
- logStep(chalk.green('Please verify the changes before committing.'));
151
- }
152
- if (warnings.length > 0) {
153
- logWarning(chalk.yellow('Warnings encountered:') +
154
- '\n' +
155
- warnings
156
- .map((warning) => `${chalk.yellow('-')} ${warning}`)
157
- .join('\n'));
158
- }
159
- }
160
- async handleValidate(initOptions, files) {
161
- validateConfigExists();
162
- const settings = await generateSettings(initOptions);
163
- // First run the base class's handleTranslate method
164
- const options = { ...initOptions, ...settings };
165
- const pkg = this.library === 'gt-next' ? 'gt-next' : 'gt-react';
166
- if (files && files.length > 0) {
167
- // Validate specific files using createInlineUpdates
168
- await validateProject(options, pkg, files);
169
- }
170
- else {
171
- // Validate whole project as before
172
- await validateProject(options, pkg);
173
- }
174
- }
175
- }
@@ -1,9 +0,0 @@
1
- import { Settings } from '../types/index.js';
2
- export declare const DEFAULT_SRC_PATTERNS: string[];
3
- /**
4
- * Generates settings from any
5
- * @param options - The options to generate settings from
6
- * @param cwd - The current working directory
7
- * @returns The generated settings
8
- */
9
- export declare function generateSettings(options: any, cwd?: string): Promise<Settings>;
@@ -1,176 +0,0 @@
1
- import { displayProjectId, logErrorAndExit, warnApiKeyInConfig, } from '../console/logging.js';
2
- import { loadConfig } from '../fs/config/loadConfig.js';
3
- import { defaultBaseUrl, libraryDefaultLocale, } from 'generaltranslation/internal';
4
- import fs from 'node:fs';
5
- import { createOrUpdateConfig } from '../fs/config/setupConfig.js';
6
- import { resolveFiles } from '../fs/config/parseFilesConfig.js';
7
- import { validateSettings } from './validateSettings.js';
8
- import { GT_DASHBOARD_URL } from '../utils/constants.js';
9
- import { resolveProjectId } from '../fs/utils.js';
10
- import path from 'node:path';
11
- import chalk from 'chalk';
12
- import { resolveConfig } from './resolveConfig.js';
13
- import { gt } from '../utils/gt.js';
14
- import { generatePreset } from './optionPresets.js';
15
- export const DEFAULT_SRC_PATTERNS = [
16
- 'src/**/*.{js,jsx,ts,tsx}',
17
- 'app/**/*.{js,jsx,ts,tsx}',
18
- 'pages/**/*.{js,jsx,ts,tsx}',
19
- 'components/**/*.{js,jsx,ts,tsx}',
20
- ];
21
- /**
22
- * Generates settings from any
23
- * @param options - The options to generate settings from
24
- * @param cwd - The current working directory
25
- * @returns The generated settings
26
- */
27
- export async function generateSettings(options, cwd = process.cwd()) {
28
- // Load config file
29
- let gtConfig = {};
30
- if (options.config && !options.config.endsWith('.json')) {
31
- options.config = `${options.config}.json`;
32
- }
33
- if (options.config) {
34
- gtConfig = loadConfig(options.config);
35
- }
36
- else {
37
- const config = resolveConfig(cwd);
38
- if (config) {
39
- gtConfig = config.config;
40
- options.config = config.path;
41
- }
42
- else {
43
- gtConfig = {};
44
- }
45
- }
46
- // Warn if apiKey is present in gt.config.json
47
- if (gtConfig.apiKey) {
48
- warnApiKeyInConfig(options.config);
49
- process.exit(1);
50
- }
51
- const projectIdEnv = resolveProjectId();
52
- // Resolve mismatched projectIds
53
- if (gtConfig.projectId &&
54
- options.projectId &&
55
- gtConfig.projectId !== options.projectId) {
56
- logErrorAndExit(`Project ID mismatch between ${chalk.green(gtConfig.projectId)} and ${chalk.green(options.projectId)}! Please use the same projectId in all configs.`);
57
- }
58
- else if (gtConfig.projectId &&
59
- projectIdEnv &&
60
- gtConfig.projectId !== projectIdEnv) {
61
- logErrorAndExit(`Project ID mismatch between ${chalk.green(gtConfig.projectId)} and ${chalk.green(projectIdEnv)}! Please use the same projectId in all configs.`);
62
- }
63
- if (options.options?.docsUrlPattern &&
64
- !options.options?.docsUrlPattern.includes('[locale]')) {
65
- logErrorAndExit('Failed to localize static urls: URL pattern must include "[locale]" to denote the location of the locale');
66
- }
67
- if (options.options?.docsImportPattern &&
68
- !options.options?.docsImportPattern.includes('[locale]')) {
69
- logErrorAndExit('Failed to localize static imports: Import pattern must include "[locale]" to denote the location of the locale');
70
- }
71
- if (options.options?.copyFiles) {
72
- for (const file of options.options.copyFiles) {
73
- if (!file.includes('[locale]')) {
74
- logErrorAndExit('Failed to copy files: File path must include "[locale]" to denote the location of the locale');
75
- }
76
- }
77
- }
78
- // merge options
79
- const mergedOptions = { ...gtConfig, ...options };
80
- // Add defaultLocale if not provided
81
- mergedOptions.defaultLocale =
82
- mergedOptions.defaultLocale || libraryDefaultLocale;
83
- // merge locales
84
- mergedOptions.locales = Array.from(new Set([...(gtConfig.locales || []), ...(options.locales || [])]));
85
- // Separate defaultLocale from locales
86
- mergedOptions.locales = mergedOptions.locales.filter((locale) => locale !== mergedOptions.defaultLocale);
87
- // Add apiKey if not provided
88
- mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;
89
- // Add projectId if not provided
90
- mergedOptions.projectId = mergedOptions.projectId || resolveProjectId();
91
- // Add baseUrl if not provided
92
- mergedOptions.baseUrl = mergedOptions.baseUrl || defaultBaseUrl;
93
- // Add dashboardUrl if not provided
94
- mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || GT_DASHBOARD_URL;
95
- // Add locales if not provided
96
- mergedOptions.locales = mergedOptions.locales || [];
97
- // Add default config file name if not provided
98
- mergedOptions.config =
99
- mergedOptions.config || path.join(cwd, 'gt.config.json');
100
- // Display projectId if present
101
- if (mergedOptions.projectId)
102
- displayProjectId(mergedOptions.projectId);
103
- // Add stageTranslations if not provided
104
- // For human review, always stage the project
105
- mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;
106
- // Add publish if not provided
107
- mergedOptions.publish = (gtConfig.publish || options.publish) ?? false;
108
- // Populate src if not provided
109
- mergedOptions.src = mergedOptions.src || DEFAULT_SRC_PATTERNS;
110
- // Resolve all glob patterns in the files object
111
- const compositePatterns = [
112
- ...Object.entries(mergedOptions.options?.jsonSchema || {}),
113
- ]
114
- .filter(([, schema]) => schema.composite)
115
- .map(([key]) => key);
116
- mergedOptions.files = mergedOptions.files
117
- ? resolveFiles(mergedOptions.files, mergedOptions.defaultLocale, mergedOptions.locales, cwd, compositePatterns)
118
- : undefined;
119
- mergedOptions.options = {
120
- ...(mergedOptions.options || {}),
121
- experimentalLocalizeStaticImports: gtConfig.options?.experimentalLocalizeStaticImports ||
122
- options.experimentalLocalizeStaticImports,
123
- experimentalLocalizeStaticUrls: gtConfig.options?.experimentalLocalizeStaticUrls ||
124
- options.experimentalLocalizeStaticUrls,
125
- experimentalHideDefaultLocale: gtConfig.options?.experimentalHideDefaultLocale ||
126
- options.experimentalHideDefaultLocale,
127
- experimentalFlattenJsonFiles: gtConfig.options?.experimentalFlattenJsonFiles ||
128
- options.experimentalFlattenJsonFiles,
129
- };
130
- // Add additional options if provided
131
- if (mergedOptions.options) {
132
- if (mergedOptions.options.jsonSchema) {
133
- for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {
134
- const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];
135
- if (jsonSchema.preset) {
136
- mergedOptions.options.jsonSchema[fileGlob] = {
137
- ...generatePreset(jsonSchema.preset, 'json'),
138
- ...jsonSchema,
139
- };
140
- }
141
- }
142
- }
143
- if (mergedOptions.options.yamlSchema) {
144
- for (const fileGlob of Object.keys(mergedOptions.options.yamlSchema)) {
145
- const yamlSchema = mergedOptions.options.yamlSchema[fileGlob];
146
- if (yamlSchema.preset) {
147
- mergedOptions.options.yamlSchema[fileGlob] = {
148
- ...generatePreset(yamlSchema.preset, 'yaml'),
149
- ...yamlSchema,
150
- };
151
- }
152
- }
153
- }
154
- }
155
- // if there's no existing config file, creates one
156
- // does not include the API key to avoid exposing it
157
- if (!fs.existsSync(mergedOptions.config)) {
158
- await createOrUpdateConfig(mergedOptions.config, {
159
- projectId: mergedOptions.projectId,
160
- defaultLocale: mergedOptions.defaultLocale,
161
- locales: mergedOptions.locales?.length > 0 ? mergedOptions.locales : undefined,
162
- framework: mergedOptions.framework,
163
- });
164
- }
165
- mergedOptions.configDirectory = path.join(cwd, '.gt');
166
- validateSettings(mergedOptions);
167
- // Set up GT instance
168
- gt.setConfig({
169
- projectId: mergedOptions.projectId,
170
- apiKey: mergedOptions.apiKey,
171
- baseUrl: mergedOptions.baseUrl,
172
- sourceLocale: mergedOptions.defaultLocale,
173
- customMapping: mergedOptions.customMapping,
174
- });
175
- return mergedOptions;
176
- }
@@ -1,2 +0,0 @@
1
- import { JsonSchema, YamlSchema } from '../types/index.js';
2
- export declare function generatePreset(preset: string, type: 'json' | 'yaml'): JsonSchema | YamlSchema;
@@ -1,56 +0,0 @@
1
- export function generatePreset(preset, type) {
2
- if (type === 'json') {
3
- switch (preset) {
4
- case 'mintlify':
5
- // https://mintlify.com/docs/navigation
6
- return {
7
- composite: {
8
- '$.navigation.languages': {
9
- type: 'array',
10
- key: '$.language',
11
- include: [
12
- '$..group',
13
- '$..tab',
14
- '$..item',
15
- '$..anchor',
16
- '$..dropdown',
17
- ],
18
- transform: {
19
- '$..pages[*]': {
20
- match: '^{locale}/(.*)$',
21
- replace: '{locale}/$1',
22
- },
23
- },
24
- },
25
- '$.redirects': {
26
- type: 'array',
27
- key: '$.language',
28
- include: [],
29
- transform: {
30
- '$.source': {
31
- match: '^/{locale}/(.*)$',
32
- replace: '/{locale}/$1',
33
- },
34
- '$.destination': {
35
- match: '^/{locale}/(.*)$',
36
- replace: '/{locale}/$1',
37
- },
38
- },
39
- },
40
- },
41
- };
42
- default:
43
- return {};
44
- }
45
- }
46
- else {
47
- switch (preset) {
48
- case 'mintlify':
49
- return {
50
- include: ['$..summary', '$..description'],
51
- };
52
- default:
53
- return {};
54
- }
55
- }
56
- }
@@ -1,4 +0,0 @@
1
- export declare function resolveConfig(cwd: string): {
2
- path: string;
3
- config: Record<string, any>;
4
- } | null;
@@ -1,19 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { loadConfig } from '../fs/config/loadConfig.js';
4
- export function resolveConfig(cwd) {
5
- const configFilepath = 'gt.config.json';
6
- if (fs.existsSync(path.join(cwd, configFilepath))) {
7
- return {
8
- path: path.join(cwd, configFilepath),
9
- config: loadConfig(path.join(cwd, configFilepath)),
10
- };
11
- }
12
- if (fs.existsSync(path.join(cwd, 'src/gt.config.json'))) {
13
- return {
14
- path: path.join(cwd, 'src/gt.config.json'),
15
- config: loadConfig(path.join(cwd, 'src/gt.config.json')),
16
- };
17
- }
18
- return null;
19
- }
@@ -1,2 +0,0 @@
1
- import { Settings } from '../types/index.js';
2
- export declare function isUsingLocalTranslations(settings: Settings): boolean;
@@ -1,4 +0,0 @@
1
- // returns true if the project is configured to use local translations
2
- export function isUsingLocalTranslations(settings) {
3
- return !!(settings.files && settings.files.placeholderPaths.gt);
4
- }
@@ -1,3 +0,0 @@
1
- import { Settings } from '../types/index.js';
2
- export declare function validateSettings(settings: Settings): void;
3
- export declare function validateConfigExists(): string;
@@ -1,32 +0,0 @@
1
- import { isValidLocale, isSupersetLocale } from 'generaltranslation';
2
- import { logErrorAndExit } from '../console/logging.js';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- export function validateSettings(settings) {
6
- // Validate locales
7
- for (const locale of settings.locales) {
8
- if (!isValidLocale(locale, settings.customMapping)) {
9
- logErrorAndExit(`Provided locales: "${settings?.locales?.join()}", ${locale} is not a valid locale!`);
10
- }
11
- }
12
- if (settings.defaultLocale &&
13
- !isValidLocale(settings.defaultLocale, settings.customMapping)) {
14
- logErrorAndExit(`defaultLocale: ${settings.defaultLocale} is not a valid locale!`);
15
- }
16
- // defaultLocale cannot be a superset of any other locale
17
- if (settings.defaultLocale &&
18
- settings.locales.some((locale) => isSupersetLocale(settings.defaultLocale, locale) &&
19
- !isSupersetLocale(locale, settings.defaultLocale))) {
20
- const locale = settings.locales.find((locale) => isSupersetLocale(settings.defaultLocale, locale));
21
- logErrorAndExit(`defaultLocale: ${settings.defaultLocale} is a superset of another locale (${locale})! Please change the defaultLocale to a more specific locale.`);
22
- }
23
- }
24
- export function validateConfigExists() {
25
- const possibleConfigPaths = ['gt.config.json', 'src/gt.config.json'];
26
- for (const possibleConfigPath of possibleConfigPaths) {
27
- if (fs.existsSync(path.resolve(path.relative(process.cwd(), possibleConfigPath)))) {
28
- return possibleConfigPath;
29
- }
30
- }
31
- logErrorAndExit('No gt.config.json file found. Are you in the correct directory?');
32
- }
@@ -1,5 +0,0 @@
1
- export declare function colorizeFilepath(filepath: string): string;
2
- export declare function colorizeComponent(component: string): string;
3
- export declare function colorizeIdString(id: string): string;
4
- export declare function colorizeContent(content: string): string;
5
- export declare function colorizeLine(line: string): string;
@@ -1,16 +0,0 @@
1
- import chalk from 'chalk';
2
- export function colorizeFilepath(filepath) {
3
- return chalk.cyan(filepath);
4
- }
5
- export function colorizeComponent(component) {
6
- return chalk.yellow(component);
7
- }
8
- export function colorizeIdString(id) {
9
- return chalk.yellow(id);
10
- }
11
- export function colorizeContent(content) {
12
- return chalk.yellow(content);
13
- }
14
- export function colorizeLine(line) {
15
- return chalk.dim(line);
16
- }
@@ -1,21 +0,0 @@
1
- export declare const warnApiKeyInConfigSync: (optionsFilepath: string) => string;
2
- export declare const warnVariablePropSync: (file: string, attrName: string, value: string, location?: string) => string;
3
- export declare const warnHasUnwrappedExpressionSync: (file: string, unwrappedExpressions: string[], id?: string, location?: string) => string;
4
- export declare const warnNestedTComponent: (file: string, location?: string) => string;
5
- export declare const warnNonStaticExpressionSync: (file: string, attrName: string, value: string, location?: string) => string;
6
- export declare const warnTemplateLiteralSync: (file: string, value: string, location?: string) => string;
7
- export declare const warnNonStringSync: (file: string, value: string, location?: string) => string;
8
- export declare const warnAsyncUseGT: (file: string, location?: string) => string;
9
- export declare const warnSyncGetGT: (file: string, location?: string) => string;
10
- export declare const warnTernarySync: (file: string, location?: string) => string;
11
- export declare const withLocation: (file: string, message: string, location?: string) => string;
12
- export declare const noLocalesError = "No locales found! Please provide a list of locales to translate to, or specify them in your gt.config.json file.";
13
- export declare const noDefaultLocaleError = "No default locale found! Please provide a default locale, or specify it in your gt.config.json file.";
14
- export declare const noFilesError = "Incorrect or missing files configuration! Please make sure your files are configured correctly in your gt.config.json file.";
15
- export declare const noSourceFileError = "No source file found! Please double check your translations directory and default locale.";
16
- export declare const noSupportedFormatError = "Unsupported data format! Please make sure your translationsDir parameter ends with a supported file extension.";
17
- export declare const noApiKeyError = "No API key found! Please provide an API key using the --api-key flag or set the GT_API_KEY environment variable.";
18
- export declare const devApiKeyError = "You are using a development API key. Please use a production API key to use the General Translation API.\nYou can generate a production API key with the command: npx gtx-cli auth -t production";
19
- export declare const noProjectIdError = "No project ID found! Please provide a project ID using the --project-id flag, specify it in your gt.config.json file, or set the GT_PROJECT_ID environment variable.";
20
- export declare const noVersionIdError = "No version ID found! Please provide a version ID using the --version-id flag or specify it in your gt.config.json file as the _versionId property.";
21
- export declare const invalidConfigurationError = "Invalid files configuration! Please either provide a valid configuration to download local translations or set the --publish flag to true to upload translations to the CDN.";
@@ -1,24 +0,0 @@
1
- import { colorizeFilepath, colorizeComponent, colorizeIdString, colorizeContent, colorizeLine, } from './colors.js';
2
- // Synchronous wrappers for backward compatibility
3
- export const warnApiKeyInConfigSync = (optionsFilepath) => `${colorizeFilepath(optionsFilepath)}: Your API key is exposed! Please remove it from the file and include it as an environment variable.`;
4
- export const warnVariablePropSync = (file, attrName, value, location) => withLocation(file, `${colorizeComponent('<T>')} component has dynamic attribute ${colorizeIdString(attrName)} with value: ${colorizeContent(value)}. Change ${colorizeIdString(attrName)} to ensure this content is translated.`, location);
5
- export const warnHasUnwrappedExpressionSync = (file, unwrappedExpressions, id, location) => withLocation(file, `${colorizeComponent('<T>')} component${id ? ` with id ${colorizeIdString(id)}` : ''} has children that could change at runtime. Use a variable component like ${colorizeComponent('<Var>')} to ensure this content is translated.\n${colorizeContent(unwrappedExpressions.join('\n'))}`, location);
6
- export const warnNestedTComponent = (file, location) => withLocation(file, `Found nested <T> component. <T> components cannot be directly nested.`, location);
7
- export const warnNonStaticExpressionSync = (file, attrName, value, location) => withLocation(file, `Found non-static expression for attribute ${colorizeIdString(attrName)}: ${colorizeContent(value)}. Change "${colorizeIdString(attrName)}" to ensure this content is translated.`, location);
8
- export const warnTemplateLiteralSync = (file, value, location) => withLocation(file, `Found template literal with quasis (${colorizeContent(value)}). Change the template literal to a string to ensure this content is translated.`, location);
9
- export const warnNonStringSync = (file, value, location) => withLocation(file, `Found non-string literal (${colorizeContent(value)}). Change the value to a string literal to ensure this content is translated.`, location);
10
- export const warnAsyncUseGT = (file, location) => withLocation(file, `Found useGT() in an async function. Use getGT() instead, or make the function synchronous.`, location);
11
- export const warnSyncGetGT = (file, location) => withLocation(file, `Found getGT() in a synchronous function. Use useGT() instead, or make the function async.`, location);
12
- export const warnTernarySync = (file, location) => withLocation(file, 'Found ternary expression. A Branch component may be more appropriate here.', location);
13
- export const withLocation = (file, message, location) => `${colorizeFilepath(file)}${location ? ` (${colorizeLine(location)})` : ''}: ${message}`;
14
- // Re-export error messages
15
- export const noLocalesError = `No locales found! Please provide a list of locales to translate to, or specify them in your gt.config.json file.`;
16
- export const noDefaultLocaleError = `No default locale found! Please provide a default locale, or specify it in your gt.config.json file.`;
17
- export const noFilesError = `Incorrect or missing files configuration! Please make sure your files are configured correctly in your gt.config.json file.`;
18
- export const noSourceFileError = `No source file found! Please double check your translations directory and default locale.`;
19
- export const noSupportedFormatError = `Unsupported data format! Please make sure your translationsDir parameter ends with a supported file extension.`;
20
- export const noApiKeyError = `No API key found! Please provide an API key using the --api-key flag or set the GT_API_KEY environment variable.`;
21
- export const devApiKeyError = `You are using a development API key. Please use a production API key to use the General Translation API.\nYou can generate a production API key with the command: npx gtx-cli auth -t production`;
22
- export const noProjectIdError = `No project ID found! Please provide a project ID using the --project-id flag, specify it in your gt.config.json file, or set the GT_PROJECT_ID environment variable.`;
23
- export const noVersionIdError = `No version ID found! Please provide a version ID using the --version-id flag or specify it in your gt.config.json file as the _versionId property.`;
24
- export const invalidConfigurationError = `Invalid files configuration! Please either provide a valid configuration to download local translations or set the --publish flag to true to upload translations to the CDN.`;
@@ -1,53 +0,0 @@
1
- export declare function logInfo(message: string): void;
2
- export declare function logWarning(message: string): void;
3
- export declare function logError(message: string): void;
4
- export declare function logSuccess(message: string): void;
5
- export declare function logStep(message: string): void;
6
- export declare function logMessage(message: string): void;
7
- export declare function logErrorAndExit(message: string): never;
8
- export declare function exit(code: number): never;
9
- export declare function startCommand(message: string): void;
10
- export declare function endCommand(message: string): void;
11
- export declare function displayHeader(introString?: string): void;
12
- export declare function displayProjectId(projectId: string): void;
13
- export declare function displayResolvedPaths(resolvedPaths: [string, string][]): void;
14
- export declare function displayCreatedConfigFile(configFilepath: string): void;
15
- export declare function displayUpdatedConfigFile(configFilepath: string): void;
16
- export declare function displayUpdatedVersionsFile(versionFilepath: string): void;
17
- export declare function createSpinner(indicator?: 'dots' | 'timer'): import("@clack/prompts").SpinnerResult;
18
- export declare function createOraSpinner(indicator?: 'dots' | 'circleHalves'): Promise<import("ora").Ora>;
19
- export declare function promptText({ message, defaultValue, validate, }: {
20
- message: string;
21
- defaultValue?: string;
22
- validate?: (value: string) => boolean | string;
23
- }): Promise<string>;
24
- export declare function promptSelect<T>({ message, options, defaultValue, }: {
25
- message: string;
26
- options: Array<{
27
- value: T;
28
- label: string;
29
- hint?: string;
30
- }>;
31
- defaultValue?: T;
32
- }): Promise<T>;
33
- export declare function promptMultiSelect<T extends string>({ message, options, required, }: {
34
- message: string;
35
- options: Array<{
36
- value: T;
37
- label: string;
38
- hint?: string;
39
- }>;
40
- required?: boolean;
41
- }): Promise<T[]>;
42
- export declare function promptConfirm({ message, defaultValue, cancelMessage, }: {
43
- message: string;
44
- defaultValue?: boolean;
45
- cancelMessage?: string;
46
- }): Promise<boolean>;
47
- export declare function warnApiKeyInConfig(optionsFilepath: string): void;
48
- export declare function warnVariableProp(file: string, attrName: string, value: string): void;
49
- export declare function warnNoId(file: string): void;
50
- export declare function warnHasUnwrappedExpression(file: string, id: string, unwrappedExpressions: string[]): void;
51
- export declare function warnNonStaticExpression(file: string, attrName: string, value: string): void;
52
- export declare function warnTemplateLiteral(file: string, value: string): void;
53
- export declare function warnTernary(file: string): void;