gtx-cli 2.3.5 → 2.3.6-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 (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
@@ -1,260 +0,0 @@
1
- import { unified } from 'unified';
2
- import remarkParse from 'remark-parse';
3
- import remarkMdx from 'remark-mdx';
4
- import remarkFrontmatter from 'remark-frontmatter';
5
- import remarkStringify from 'remark-stringify';
6
- import { visit } from 'unist-util-visit';
7
- import { logWarning } from '../console/logging.js';
8
- import escapeHtmlInTextNodes from 'gt-remark';
9
- /**
10
- * Generates a slug from heading text
11
- */
12
- function generateSlug(text) {
13
- return text
14
- .toLowerCase()
15
- .replace(/[^\w\s-]/g, '') // Remove special chars except spaces and hyphens
16
- .trim()
17
- .replace(/\s+/g, '-') // Replace spaces with hyphens
18
- .replace(/-+/g, '-') // Replace multiple hyphens with single hyphen
19
- .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
20
- }
21
- /**
22
- * Extracts text content from heading nodes
23
- */
24
- function extractHeadingText(heading) {
25
- let text = '';
26
- visit(heading, ['text', 'inlineCode'], (node) => {
27
- if ('value' in node && typeof node.value === 'string') {
28
- text += node.value;
29
- }
30
- });
31
- return text;
32
- }
33
- /**
34
- * Checks if a heading is already wrapped in a div with id
35
- */
36
- function hasExplicitId(heading, ast) {
37
- const lastChild = heading.children[heading.children.length - 1];
38
- if (lastChild?.type === 'text') {
39
- return /(\{#[^}]+\}|\[[^\]]+\])$/.test(lastChild.value);
40
- }
41
- return false;
42
- }
43
- /**
44
- * Extracts heading information from content (read-only, no modifications)
45
- */
46
- export function extractHeadingInfo(mdxContent) {
47
- const headings = [];
48
- // Parse the MDX content into an AST
49
- let processedAst;
50
- try {
51
- const parseProcessor = unified()
52
- .use(remarkParse)
53
- .use(remarkFrontmatter, ['yaml', 'toml'])
54
- .use(remarkMdx);
55
- const ast = parseProcessor.parse(mdxContent);
56
- processedAst = parseProcessor.runSync(ast);
57
- }
58
- catch (error) {
59
- console.warn(`Failed to parse MDX content: ${error instanceof Error ? error.message : String(error)}`);
60
- return [];
61
- }
62
- let position = 0;
63
- visit(processedAst, 'heading', (heading) => {
64
- const headingText = extractHeadingText(heading);
65
- if (headingText) {
66
- const slug = generateSlug(headingText);
67
- headings.push({
68
- text: headingText,
69
- level: heading.depth,
70
- slug,
71
- position: position++,
72
- });
73
- }
74
- });
75
- return headings;
76
- }
77
- /**
78
- * Applies anchor IDs to translated content based on source heading mapping
79
- */
80
- export function addExplicitAnchorIds(translatedContent, sourceHeadingMap, settings, sourcePath, translatedPath) {
81
- const addedIds = [];
82
- const useDivWrapping = settings?.options?.experimentalAddHeaderAnchorIds === 'mintlify';
83
- // Extract headings from translated content
84
- const translatedHeadings = extractHeadingInfo(translatedContent);
85
- // Pre-processing validation: check if header counts match
86
- if (sourceHeadingMap.length !== translatedHeadings.length) {
87
- const sourceFile = sourcePath
88
- ? `Source file: ${sourcePath}`
89
- : 'Source file';
90
- const translatedFile = translatedPath
91
- ? `translated file: ${translatedPath}`
92
- : 'translated file';
93
- logWarning(`Header count mismatch detected! ${sourceFile} has ${sourceHeadingMap.length} headers but ${translatedFile} has ${translatedHeadings.length} headers. ` +
94
- `This likely means your source file was edited after translation was requested, causing a mismatch between ` +
95
- `the number of headers in your source file vs the translated file. Please re-translate this file to resolve the issue.`);
96
- }
97
- // Create ID mapping based on positional matching
98
- const idMappings = new Map();
99
- sourceHeadingMap.forEach((sourceHeading, index) => {
100
- const translatedHeading = translatedHeadings[index];
101
- // Match by position and level for safety
102
- if (translatedHeading && translatedHeading.level === sourceHeading.level) {
103
- idMappings.set(index, sourceHeading.slug);
104
- addedIds.push({
105
- heading: translatedHeading.text,
106
- id: sourceHeading.slug,
107
- });
108
- }
109
- });
110
- if (idMappings.size === 0) {
111
- return {
112
- content: translatedContent,
113
- hasChanges: false,
114
- addedIds: [],
115
- };
116
- }
117
- // Apply IDs to translated content
118
- let content;
119
- if (useDivWrapping) {
120
- content = applyDivWrappedIds(translatedContent, translatedHeadings, idMappings);
121
- }
122
- else {
123
- content = applyInlineIds(translatedContent, idMappings);
124
- }
125
- return {
126
- content,
127
- hasChanges: addedIds.length > 0,
128
- addedIds,
129
- };
130
- }
131
- /**
132
- * Adds inline {#id} syntax to headings (standard markdown approach)
133
- */
134
- function applyInlineIds(translatedContent, idMappings) {
135
- // Parse the translated content
136
- let processedAst;
137
- try {
138
- const parseProcessor = unified()
139
- .use(remarkParse)
140
- .use(remarkFrontmatter, ['yaml', 'toml'])
141
- .use(remarkMdx);
142
- const ast = parseProcessor.parse(translatedContent);
143
- processedAst = parseProcessor.runSync(ast);
144
- }
145
- catch (error) {
146
- console.warn(`Failed to parse translated MDX content: ${error instanceof Error ? error.message : String(error)}`);
147
- return translatedContent;
148
- }
149
- // Apply IDs to headings based on position
150
- let headingIndex = 0;
151
- visit(processedAst, 'heading', (heading) => {
152
- const id = idMappings.get(headingIndex);
153
- if (id) {
154
- // Skip if heading already has explicit ID
155
- if (hasExplicitId(heading, processedAst)) {
156
- headingIndex++;
157
- return;
158
- }
159
- // Add the ID to the heading
160
- const lastChild = heading.children[heading.children.length - 1];
161
- if (lastChild?.type === 'text') {
162
- lastChild.value += ` \\{#${id}\\}`;
163
- }
164
- else {
165
- // If last child is not text, add a new text node
166
- heading.children.push({
167
- type: 'text',
168
- value: ` \\{#${id}\\}`,
169
- });
170
- }
171
- }
172
- headingIndex++;
173
- });
174
- // Convert the modified AST back to MDX string
175
- try {
176
- const stringifyProcessor = unified()
177
- .use(remarkFrontmatter, ['yaml', 'toml'])
178
- .use(remarkMdx)
179
- .use(escapeHtmlInTextNodes)
180
- .use(remarkStringify, {
181
- handlers: {
182
- // Custom handler to prevent escaping of {#id} syntax
183
- text(node) {
184
- return node.value;
185
- },
186
- },
187
- });
188
- const outTree = stringifyProcessor.runSync(processedAst);
189
- let content = stringifyProcessor.stringify(outTree);
190
- // Handle newline formatting to match original input
191
- if (content.endsWith('\n') && !translatedContent.endsWith('\n')) {
192
- content = content.slice(0, -1);
193
- }
194
- // Preserve leading newlines from original content
195
- if (translatedContent.startsWith('\n') && !content.startsWith('\n')) {
196
- content = '\n' + content;
197
- }
198
- return content;
199
- }
200
- catch (error) {
201
- console.warn(`Failed to stringify translated MDX content: ${error instanceof Error ? error.message : String(error)}`);
202
- return translatedContent;
203
- }
204
- }
205
- /**
206
- * Wraps headings in divs with IDs (Mintlify approach)
207
- */
208
- function applyDivWrappedIds(translatedContent, translatedHeadings, idMappings) {
209
- // Extract all heading lines from the translated markdown
210
- const lines = translatedContent.split('\n');
211
- const headingLines = [];
212
- lines.forEach((line, index) => {
213
- const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
214
- if (headingMatch) {
215
- const level = headingMatch[1].length;
216
- headingLines.push({ line, level, index });
217
- }
218
- });
219
- // Use string-based approach to wrap headings in divs
220
- let content = translatedContent;
221
- const headingsToWrap = [];
222
- // Match translated headings with their corresponding lines by position and level
223
- translatedHeadings.forEach((heading, position) => {
224
- const id = idMappings.get(position);
225
- if (id) {
226
- // Find the corresponding original line for this heading
227
- const matchingLine = headingLines.find((hl) => {
228
- // Extract clean text from the original line for comparison
229
- const lineCleanText = hl.line.replace(/^#{1,6}\s+/, '').trim();
230
- // Create a version without markdown formatting for comparison
231
- const cleanLineText = lineCleanText
232
- .replace(/\*\*(.*?)\*\*/g, '$1') // Remove bold
233
- .replace(/\*(.*?)\*/g, '$1') // Remove italic
234
- .replace(/`(.*?)`/g, '$1') // Remove inline code
235
- .replace(/\[(.*?)\]\(.*?\)/g, '$1') // Remove links, keep text
236
- .trim();
237
- return cleanLineText === heading.text && hl.level === heading.level;
238
- });
239
- if (matchingLine) {
240
- headingsToWrap.push({
241
- originalLine: matchingLine.line,
242
- id,
243
- });
244
- }
245
- }
246
- });
247
- if (headingsToWrap.length > 0) {
248
- // Process headings from longest to shortest original line to avoid partial matches
249
- const sortedHeadings = headingsToWrap.sort((a, b) => b.originalLine.length - a.originalLine.length);
250
- for (const heading of sortedHeadings) {
251
- // Escape the original line for use in regex
252
- const escapedLine = heading.originalLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
253
- const headingPattern = new RegExp(`^${escapedLine}\\s*$`, 'gm');
254
- content = content.replace(headingPattern, (match) => {
255
- return `<div id="${heading.id}">\n ${match.trim()}\n</div>\n`;
256
- });
257
- }
258
- }
259
- return content;
260
- }
@@ -1,2 +0,0 @@
1
- export declare const GT_DASHBOARD_URL = "https://dash.generaltranslation.com";
2
- export declare const GT_CONFIG_SCHEMA_URL = "https://assets.gtx.dev/config-schema.json";
@@ -1,2 +0,0 @@
1
- export const GT_DASHBOARD_URL = 'https://dash.generaltranslation.com';
2
- export const GT_CONFIG_SCHEMA_URL = 'https://assets.gtx.dev/config-schema.json';
@@ -1,12 +0,0 @@
1
- import { Settings, SupportedFrameworks } from '../types/index.js';
2
- type Credentials = {
3
- apiKey: string;
4
- projectId: string;
5
- };
6
- export declare function retrieveCredentials(settings: Settings, keyType: 'development' | 'production'): Promise<Credentials>;
7
- export declare function generateCredentialsSession(url: string, keyType: 'development' | 'production'): Promise<{
8
- sessionId: string;
9
- }>;
10
- export declare function areCredentialsSet(): string | undefined;
11
- export declare function setCredentials(credentials: Credentials, type: 'development' | 'production', framework?: SupportedFrameworks, cwd?: string): Promise<void>;
12
- export {};
@@ -1,119 +0,0 @@
1
- import { createSpinner, logErrorAndExit, logMessage, } from '../console/logging.js';
2
- import path from 'node:path';
3
- import fs from 'node:fs';
4
- import chalk from 'chalk';
5
- // Fetches project ID and API key by opening the dashboard in the browser
6
- export async function retrieveCredentials(settings, keyType) {
7
- // Generate a session ID
8
- const { sessionId } = await generateCredentialsSession(settings.baseUrl, keyType);
9
- const urlToOpen = `${settings.dashboardUrl}/cli/wizard/${sessionId}`;
10
- await import('open').then((open) => open.default(urlToOpen, {
11
- wait: false,
12
- }));
13
- logMessage(`${chalk.dim(`If the browser window didn't open automatically, please open the following link:`)}\n\n${chalk.cyan(urlToOpen)}`);
14
- const spinner = createSpinner('dots');
15
- spinner.start('Waiting for response from dashboard...');
16
- const credentials = await new Promise(async (resolve, reject) => {
17
- const interval = setInterval(async () => {
18
- // Ping the dashboard to see if the credentials are set
19
- try {
20
- const res = await fetch(`${settings.baseUrl}/cli/wizard/${sessionId}`, {
21
- method: 'GET',
22
- });
23
- if (res.status === 200) {
24
- const data = await res.json();
25
- resolve(data);
26
- clearInterval(interval);
27
- clearTimeout(timeout);
28
- fetch(`${settings.baseUrl}/cli/wizard/${sessionId}`, {
29
- method: 'DELETE',
30
- });
31
- }
32
- }
33
- catch (err) {
34
- console.error(err);
35
- }
36
- }, 2000);
37
- // timeout after 1 hour
38
- const timeout = setTimeout(() => {
39
- spinner.stop('Timed out');
40
- clearInterval(interval);
41
- logErrorAndExit('Timed out waiting for response from dashboard');
42
- }, 1000 * 60 * 60);
43
- });
44
- spinner.stop('Received credentials');
45
- return credentials;
46
- }
47
- export async function generateCredentialsSession(url, keyType) {
48
- const res = await fetch(`${url}/cli/wizard/session`, {
49
- method: 'POST',
50
- headers: {
51
- 'Content-Type': 'application/json',
52
- },
53
- body: JSON.stringify({
54
- keyType,
55
- }),
56
- });
57
- if (!res.ok) {
58
- logErrorAndExit('Failed to generate credentials session');
59
- }
60
- return await res.json();
61
- }
62
- // Checks if the credentials are set in the environment variables
63
- export function areCredentialsSet() {
64
- return process.env.GT_PROJECT_ID && process.env.GT_API_KEY;
65
- }
66
- // Sets the credentials in .env.local file
67
- export async function setCredentials(credentials, type, framework, cwd = process.cwd()) {
68
- const envFile = path.join(cwd, '.env.local');
69
- let envContent = '';
70
- // Check if .env.local exists, create it if it doesn't
71
- if (!fs.existsSync(envFile)) {
72
- // File doesn't exist, create it
73
- await fs.promises.writeFile(envFile, '', 'utf8');
74
- // Add .env.local to .gitignore if it exists
75
- const gitignoreFile = path.join(cwd, '.gitignore');
76
- if (fs.existsSync(gitignoreFile)) {
77
- const gitignoreContent = await fs.promises.readFile(gitignoreFile, 'utf8');
78
- if (!gitignoreContent.includes('.env.local')) {
79
- await fs.promises.appendFile(gitignoreFile, '\n.env.local\n', 'utf8');
80
- }
81
- }
82
- else {
83
- // Create .gitignore file with .env.local
84
- await fs.promises.writeFile(gitignoreFile, '.env.local\n', 'utf8');
85
- }
86
- }
87
- else {
88
- // Read existing content
89
- envContent = await fs.promises.readFile(envFile, 'utf8');
90
- }
91
- // Always append the credentials to the file
92
- let prefix = '';
93
- if (framework === 'next-pages') {
94
- prefix = 'NEXT_PUBLIC_';
95
- }
96
- else if (framework === 'vite') {
97
- prefix = 'VITE_';
98
- }
99
- else if (framework === 'gatsby') {
100
- prefix = 'GATSBY_';
101
- }
102
- else if (framework === 'react') {
103
- prefix = 'REACT_APP_';
104
- }
105
- else if (framework === 'redwood') {
106
- prefix = 'REDWOOD_ENV_';
107
- }
108
- envContent += `\n${prefix}GT_PROJECT_ID=${credentials.projectId}\n`;
109
- if (type === 'development') {
110
- envContent += `${prefix || ''}GT_DEV_API_KEY=${credentials.apiKey}\n`;
111
- }
112
- else {
113
- envContent += `GT_API_KEY=${credentials.apiKey}\n`;
114
- }
115
- // Ensure we don't have excessive newlines
116
- envContent = envContent.replace(/\n{3,}/g, '\n\n').trim() + '\n';
117
- // Write the updated content back to the file
118
- await fs.promises.writeFile(envFile, envContent, 'utf8');
119
- }
@@ -1,2 +0,0 @@
1
- import { Settings } from '../types/index.js';
2
- export default function flattenJsonFiles(settings: Settings): Promise<void>;
@@ -1,36 +0,0 @@
1
- import { createFileMapping } from '../formats/files/fileMapping.js';
2
- import fs from 'node:fs';
3
- export default async function flattenJsonFiles(settings) {
4
- if (!settings.files ||
5
- (Object.keys(settings.files.placeholderPaths).length === 1 &&
6
- settings.files.placeholderPaths.gt)) {
7
- return;
8
- }
9
- const { resolvedPaths: sourceFiles } = settings.files;
10
- const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.locales, settings.defaultLocale);
11
- await Promise.all(Object.values(fileMapping).map(async (filesMap) => {
12
- const targetFiles = Object.values(filesMap).filter((path) => path.endsWith('.json'));
13
- await Promise.all(targetFiles.map(async (file) => {
14
- // Read each json file
15
- const json = JSON.parse(fs.readFileSync(file, 'utf8'));
16
- // Flatten the json
17
- const flattenedJson = flattenJson(json);
18
- // Write the flattened json to the target file
19
- await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
20
- return flattenedJson;
21
- }));
22
- }));
23
- }
24
- function flattenJson(json, prefix = '') {
25
- const result = {};
26
- for (const [key, value] of Object.entries(json)) {
27
- const newKey = prefix ? `${prefix}.${key}` : key;
28
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
29
- Object.assign(result, flattenJson(value, newKey));
30
- }
31
- else {
32
- result[newKey] = value;
33
- }
34
- }
35
- return result;
36
- }
@@ -1,2 +0,0 @@
1
- import { GT } from 'generaltranslation';
2
- export declare const gt: GT;
package/dist/utils/gt.js DELETED
@@ -1,2 +0,0 @@
1
- import { GT } from 'generaltranslation';
2
- export const gt = new GT();
@@ -1,6 +0,0 @@
1
- /**
2
- * Hashes a string using SHA-256 algorithm.
3
- * @param {string} string - The string to be hashed.
4
- * @returns {string} The hashed string.
5
- */
6
- export declare function hashStringSync(string: string): string;
@@ -1,11 +0,0 @@
1
- import crypto from 'crypto';
2
- /**
3
- * Hashes a string using SHA-256 algorithm.
4
- * @param {string} string - The string to be hashed.
5
- * @returns {string} The hashed string.
6
- */
7
- export function hashStringSync(string) {
8
- const hash = crypto.createHash('sha256');
9
- hash.update(string);
10
- return hash.digest('hex');
11
- }
@@ -1 +0,0 @@
1
- export declare function getAuthHeaders(projectId: string, apiKey: string): Record<string, string>;
@@ -1,14 +0,0 @@
1
- export function getAuthHeaders(projectId, apiKey) {
2
- const authHeaders = {
3
- 'x-gt-project-id': projectId,
4
- };
5
- if (apiKey) {
6
- if (apiKey.startsWith('gtx-internal-')) {
7
- authHeaders['x-gt-internal-api-key'] = apiKey;
8
- }
9
- else {
10
- authHeaders['x-gt-api-key'] = apiKey;
11
- }
12
- }
13
- return authHeaders;
14
- }
@@ -1,3 +0,0 @@
1
- import { PackageManager } from './packageManager.js';
2
- export declare function installPackage(packageName: string, packageManager: PackageManager, asDevDependency?: boolean, cwd?: string): Promise<void>;
3
- export declare function installPackageGlobal(packageName: string, version?: string): Promise<void>;
@@ -1,77 +0,0 @@
1
- import chalk from 'chalk';
2
- import { spawn } from 'child_process';
3
- import { logError, logInfo } from '../console/logging.js';
4
- export async function installPackage(packageName, packageManager, asDevDependency, cwd = process.cwd()) {
5
- return new Promise((resolve, reject) => {
6
- const command = packageManager.name;
7
- const args = [packageManager.installCommand, packageName];
8
- if (asDevDependency) {
9
- args.push(packageManager.devDependencyFlag);
10
- }
11
- const childProcess = spawn(command, args, {
12
- stdio: ['pipe', 'ignore', 'pipe'],
13
- cwd,
14
- });
15
- let errorOutput = '';
16
- if (childProcess.stderr) {
17
- childProcess.stderr.on('data', (data) => {
18
- errorOutput += data.toString();
19
- });
20
- }
21
- childProcess.on('error', (error) => {
22
- logError(chalk.red(`Installation error: ${error.message}`));
23
- logInfo(`Please manually install ${packageName} with: ${packageManager.name} ${packageManager.installCommand} ${packageName}`);
24
- reject(error);
25
- });
26
- childProcess.on('close', (code) => {
27
- if (code === 0) {
28
- resolve();
29
- }
30
- else {
31
- logError(chalk.red(`Installation failed with exit code ${code}`));
32
- if (errorOutput) {
33
- logError(chalk.red(`Error details: ${errorOutput}`));
34
- }
35
- logInfo(`Please manually install ${packageName} with: ${packageManager.name} ${packageManager.installCommand} ${packageName}`);
36
- reject(new Error(`Process exited with code ${code}`));
37
- }
38
- });
39
- });
40
- }
41
- export async function installPackageGlobal(packageName, version) {
42
- return new Promise((resolve, reject) => {
43
- const command = 'npm';
44
- const args = [
45
- 'install',
46
- '-g',
47
- version ? `${packageName}@${version}` : packageName,
48
- ];
49
- const childProcess = spawn(command, args, {
50
- stdio: ['pipe', 'ignore', 'pipe'],
51
- });
52
- let errorOutput = '';
53
- if (childProcess.stderr) {
54
- childProcess.stderr.on('data', (data) => {
55
- errorOutput += data.toString();
56
- });
57
- }
58
- childProcess.on('error', (error) => {
59
- logError(chalk.red(`Installation error: ${error.message}`));
60
- logInfo(`Please manually install ${packageName} with: npm install -g ${packageName}`);
61
- reject(error);
62
- });
63
- childProcess.on('close', (code) => {
64
- if (code === 0) {
65
- resolve();
66
- }
67
- else {
68
- logError(chalk.red(`Installation failed with exit code ${code}`));
69
- if (errorOutput) {
70
- logError(chalk.red(`Error details: ${errorOutput}`));
71
- }
72
- logInfo(`Please manually install ${packageName} with: npm install -g ${packageName}`);
73
- reject(new Error(`Process exited with code ${code}`));
74
- }
75
- });
76
- });
77
- }
@@ -1,15 +0,0 @@
1
- import { Settings } from '../types/index.js';
2
- /**
3
- * Localizes static imports in content files.
4
- * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)
5
- * @param settings - The settings object containing the project configuration.
6
- * @returns void
7
- *
8
- * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before
9
- * it can be enabled by default.
10
- *
11
- * Before this becomes a non-experimental feature, we need to:
12
- * - Support more file types
13
- * - Support more complex paths
14
- */
15
- export default function localizeStaticImports(settings: Settings): Promise<void>;