gt 2.25.2 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/api/downloadFileBatch.js +8 -9
- package/dist/api/downloadFileBatch.js.map +1 -1
- package/dist/bin/bin-entry.js +1 -1
- package/dist/cli/base.js +9 -7
- package/dist/cli/base.js.map +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/main.js +1 -1
- package/dist/setup/buildTools/index.d.ts +6 -0
- package/dist/setup/buildTools/index.js +6 -1
- package/dist/setup/buildTools/index.js.map +1 -1
- package/dist/setup/buildTools/reactRouter/index.d.ts +2 -0
- package/dist/setup/buildTools/reactRouter/index.js +127 -0
- package/dist/setup/buildTools/reactRouter/index.js.map +1 -0
- package/dist/setup/buildTools/reactRouter/root.d.ts +23 -0
- package/dist/setup/buildTools/reactRouter/root.js +218 -0
- package/dist/setup/buildTools/reactRouter/root.js.map +1 -0
- package/dist/setup/buildTools/reactRouter/source.d.ts +8 -0
- package/dist/setup/buildTools/reactRouter/source.js +106 -0
- package/dist/setup/buildTools/reactRouter/source.js.map +1 -0
- package/dist/setup/buildTools/shared/document.d.ts +29 -0
- package/dist/setup/buildTools/shared/document.js +76 -0
- package/dist/setup/buildTools/shared/document.js.map +1 -0
- package/dist/setup/buildTools/shared/edits.d.ts +1 -2
- package/dist/setup/buildTools/shared/edits.js.map +1 -1
- package/dist/setup/buildTools/shared/initializeGT.d.ts +21 -0
- package/dist/setup/buildTools/shared/initializeGT.js +50 -0
- package/dist/setup/buildTools/shared/initializeGT.js.map +1 -0
- package/dist/setup/buildTools/shared/loader.d.ts +6 -0
- package/dist/setup/buildTools/shared/loader.js +24 -0
- package/dist/setup/buildTools/shared/loader.js.map +1 -0
- package/dist/setup/buildTools/shared/source.d.ts +29 -3
- package/dist/setup/buildTools/shared/source.js +44 -7
- package/dist/setup/buildTools/shared/source.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/index.js +17 -12
- package/dist/setup/buildTools/tanstackStart/index.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/root.d.ts +1 -4
- package/dist/setup/buildTools/tanstackStart/root.js +17 -57
- package/dist/setup/buildTools/tanstackStart/root.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/router.d.ts +1 -9
- package/dist/setup/buildTools/tanstackStart/router.js +7 -39
- package/dist/setup/buildTools/tanstackStart/router.js.map +1 -1
- package/dist/setup/buildTools/vite.js +3 -11
- package/dist/setup/buildTools/vite.js.map +1 -1
- package/dist/setup/detectFramework.d.ts +1 -1
- package/dist/setup/detectFramework.js +5 -1
- package/dist/setup/detectFramework.js.map +1 -1
- package/dist/setup/developmentCredentials.js +39 -8
- package/dist/setup/developmentCredentials.js.map +1 -1
- package/dist/setup/frameworkUtils.js +1 -0
- package/dist/setup/frameworkUtils.js.map +1 -1
- package/dist/setup/wizard.js +4 -0
- package/dist/setup/wizard.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.js +2 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/constants.d.ts +1 -0
- package/dist/utils/constants.js +2 -1
- package/dist/utils/constants.js.map +1 -1
- package/dist/utils/credentials.js +2 -1
- package/dist/utils/credentials.js.map +1 -1
- package/dist/utils/loadEnv.d.ts +2 -0
- package/dist/utils/loadEnv.js +10 -9
- package/dist/utils/loadEnv.js.map +1 -1
- package/dist/utils/reactPackageCompatibility.d.ts +5 -0
- package/dist/utils/reactPackageCompatibility.js +11 -7
- package/dist/utils/reactPackageCompatibility.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.26.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2409](https://github.com/generaltranslation/gt/pull/2409) [`fe2e16a`](https://github.com/generaltranslation/gt/commit/fe2e16a904e0e9287e19be9a212e628fc3fd77fc) Thanks [@kevinwu98](https://github.com/kevinwu98)! - `gt init` now sets up React Router framework apps, including Shopify Hydrogen, with `gt-react`: it writes `app/loadTranslations.ts` and configures an `app/root.tsx` shaped like the create-react-router or Hydrogen starters to load each visitor's locale and translations in the root loader. Other roots get manual steps. SPA mode, pre-rendering, RSC Framework Mode, an `appDirectory` other than `app`, or a `gt-react` older than 11.1.3 stop setup before any change.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#2404](https://github.com/generaltranslation/gt/pull/2404) [`94ee3b4`](https://github.com/generaltranslation/gt/commit/94ee3b4b895b86db6ae942ec78621a5927d1b2f3) Thanks [@chenxin-yan](https://github.com/chenxin-yan)! - `gt init` explains a denied development key instead of reporting a generic credentials failure. When `GT_API_KEY` is set, a denied key or project creation explains that setup used that key instead of your sign-in and how to remove it.
|
|
12
|
+
|
|
13
|
+
- [#2423](https://github.com/generaltranslation/gt/pull/2423) [`98ef8cd`](https://github.com/generaltranslation/gt/commit/98ef8cd8e2fc2af495ecc45e1d126ae862fa4671) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Remove default JSON alphabetization
|
|
14
|
+
|
|
15
|
+
- [#2411](https://github.com/generaltranslation/gt/pull/2411) [`1e4135b`](https://github.com/generaltranslation/gt/commit/1e4135b754c47c37ec9dcdd7d2cb815f6d9ba2eb) Thanks [@kevinwu98](https://github.com/kevinwu98)! - `gt init` no longer leaves a TanStack Start root route for manual setup when a comment or string mentions `getLocale` or `getTranslationsSnapshot`. Only code that binds or uses those names blocks the automatic edit.
|
|
16
|
+
|
|
17
|
+
- Updated dependencies [[`fe9f4b8`](https://github.com/generaltranslation/gt/commit/fe9f4b898548b94d7809be18f5e0dd9e80987428)]:
|
|
18
|
+
- generaltranslation@9.5.6
|
|
19
|
+
- @generaltranslation/python-extractor@0.2.61
|
|
20
|
+
- @generaltranslation/supported-locales@2.1.42
|
|
21
|
+
- @generaltranslation/vue-extractor@0.1.20
|
|
22
|
+
|
|
3
23
|
## 2.25.2
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
|
@@ -19,7 +19,6 @@ import { recordDownloaded, recordRemerged } from "../state/recentDownloads.js";
|
|
|
19
19
|
import * as fs$1 from "fs";
|
|
20
20
|
import * as path$1 from "path";
|
|
21
21
|
import { isBinaryFileFormat } from "generaltranslation/types";
|
|
22
|
-
import stringify from "fast-json-stable-stringify";
|
|
23
22
|
//#region src/api/downloadFileBatch.ts
|
|
24
23
|
/**
|
|
25
24
|
* The platform withholds unapproved review-gated GTJSON components from
|
|
@@ -49,8 +48,11 @@ function countGtJsonEntries(content) {
|
|
|
49
48
|
}
|
|
50
49
|
}
|
|
51
50
|
function sortJsonString(data) {
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
return JSON.stringify(JSON.parse(data), sortKeys, 2);
|
|
52
|
+
}
|
|
53
|
+
function sortKeys(_key, value) {
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
55
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
54
56
|
}
|
|
55
57
|
/**
|
|
56
58
|
* Merges translated content with the current source file for schema-based formats.
|
|
@@ -174,11 +176,8 @@ async function downloadFileBatch(fileTracker, files, options, forceDownload = fa
|
|
|
174
176
|
} catch {}
|
|
175
177
|
const extracted = (options.options?.jsonSchema ? extractJson(existingContent, inputPath, options.options, locale, options.defaultLocale) : null) ?? (options.options?.yamlSchema ? extractYaml(existingContent, inputPath, options.options) : null);
|
|
176
178
|
if (extracted) {
|
|
177
|
-
|
|
178
|
-
if (
|
|
179
|
-
remergedData = sortJsonString(remergedData);
|
|
180
|
-
} catch {}
|
|
181
|
-
if (remergedData !== existingContent) await fs$1.promises.writeFile(outputPath, remergedData);
|
|
179
|
+
const remerged = mergeWithSource(extracted, locale, inputPath, options);
|
|
180
|
+
if (remerged !== existingContent) await fs$1.promises.writeFile(outputPath, remerged);
|
|
182
181
|
recordRemerged(outputPath);
|
|
183
182
|
}
|
|
184
183
|
} catch (error) {
|
|
@@ -192,7 +191,7 @@ async function downloadFileBatch(fileTracker, files, options, forceDownload = fa
|
|
|
192
191
|
if (isXcstringsCatalog) data = mergeXcstringsLocale(file.data, locale, inputPath);
|
|
193
192
|
else {
|
|
194
193
|
data = mergeWithSource(file.data, locale, inputPath, options);
|
|
195
|
-
if (file.fileFormat === "GTJSON"
|
|
194
|
+
if (file.fileFormat === "GTJSON") try {
|
|
196
195
|
data = sortJsonString(data);
|
|
197
196
|
} catch (error) {
|
|
198
197
|
logger.warn(`Failed to sort JSON file: ${file.id}: ` + error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"downloadFileBatch.js","names":["fs","path"],"sources":["../../src/api/downloadFileBatch.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { isBinaryFileFormat } from 'generaltranslation/types';\nimport { logger } from '../console/logger.js';\nimport { api } from '../utils/api.js';\nimport { Settings } from '../types/index.js';\nimport { validateJsonSchema } from '../formats/json/utils.js';\nimport { validateYamlSchema } from '../formats/yaml/utils.js';\nimport { mergeJson } from '../formats/json/mergeJson.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport { mergeXcstringsLocale } from '../formats/xcstrings/mergeXcstrings.js';\nimport mergeYaml from '../formats/yaml/mergeYaml.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n} from '../utils/resolveMintlifyRefs.js';\nimport {\n readLockfile,\n writeLockfile,\n findOrCreateEntry,\n} from '../fs/config/downloadedVersions.js';\nimport { recordDownloaded, recordRemerged } from '../state/recentDownloads.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport stringify from 'fast-json-stable-stringify';\nimport type { FileStatusTracker } from '../workflows/steps/PollJobsStep.js';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport { hasNonIdentityFileFormatTransformForType } from '../formats/files/transformFormat.js';\nimport { getRelative } from '../fs/findFilepath.js';\nimport { encodeFileContent } from '../fs/fileContent.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../types/libraries.js';\n\n/**\n * The platform withholds unapproved review-gated GTJSON components from\n * served output. Reports the delta between the source component count and\n * the served content so partially-served files don't read as fully\n * translated — for both fresh downloads and already-downloaded skips.\n */\nfunction reportWithheldGtJsonComponents(\n fileFormat: string | undefined,\n servedContent: string,\n componentCount: number | undefined,\n locale: string,\n inlineLibrary?: InlineLibrary\n): void {\n if (fileFormat !== 'GTJSON' || componentCount == null) return;\n const received = countGtJsonEntries(servedContent);\n if (received == null) return;\n const withheld = componentCount - received;\n if (withheld > 0) {\n recordWarning(\n 'pending_review',\n `<${getInlineElementsLabel(inlineLibrary)}>`,\n `${withheld} component translation(s) for locale ${locale} require review and are not approved yet`\n );\n }\n}\n\n/**\n * Counts entries in downloaded GTJSON output, tolerating both the flat\n * public shape and a wrapped { type, data } shape.\n */\nfunction countGtJsonEntries(content: string): number | undefined {\n try {\n const parsed: unknown = JSON.parse(content);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n const entries =\n 'type' in parsed &&\n parsed.type === 'GTJSON' &&\n 'data' in parsed &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ? parsed.data\n : parsed;\n return Object.keys(entries).length;\n } catch {\n return undefined;\n }\n}\n\nfunction sortJsonString(data: string): string {\n const sortedData = stringify(JSON.parse(data));\n return JSON.stringify(JSON.parse(sortedData), null, 2);\n}\n\n/**\n * Merges translated content with the current source file for schema-based formats.\n */\nfunction mergeWithSource(\n translatedContent: string,\n locale: string,\n inputPath: string,\n options: Settings\n): string {\n if (shouldSkipSourceFormatMerge(inputPath, options)) {\n return translatedContent;\n }\n if (!options.options) return translatedContent;\n\n const jsonSchema = options.options.jsonSchema\n ? validateJsonSchema(options.options, inputPath)\n : null;\n const yamlSchema =\n !jsonSchema && options.options.yamlSchema\n ? validateYamlSchema(options.options, inputPath)\n : null;\n\n if (!jsonSchema && !yamlSchema) return translatedContent;\n\n const sourceContent = fs.readFileSync(inputPath, 'utf8');\n if (!sourceContent) return translatedContent;\n\n if (jsonSchema) {\n // Resolve $ref before merging if configured\n let resolvedSourceContent = sourceContent;\n if (shouldResolveRefs(inputPath, options.options)) {\n try {\n const json = JSON.parse(sourceContent);\n const { resolved } = resolveMintlifyRefs(json, inputPath);\n resolvedSourceContent = JSON.stringify(resolved, null, 2);\n } catch {\n // Fall through with original content\n }\n }\n return mergeJson(\n resolvedSourceContent,\n inputPath,\n options.options,\n [{ translatedContent, targetLocale: locale }],\n options.defaultLocale,\n options.locales\n )[0];\n } else {\n return mergeYaml(\n sourceContent,\n inputPath,\n options.options,\n [{ translatedContent, targetLocale: locale }],\n options.defaultLocale\n )[0];\n }\n}\n\n/**\n * Determines whether a source file should be skipped for schema re-merging.\n * @param inputPath - The path of the source file\n * @param options - The settings for the project\n * @returns True if the source file should be skipped for schema re-merging, false otherwise\n */\nfunction shouldSkipSourceFormatMerge(\n inputPath: string,\n options: Settings\n): boolean {\n for (const fileType of SUPPORTED_FILE_EXTENSIONS) {\n if (!hasNonIdentityFileFormatTransformForType(options, fileType)) continue;\n\n const transformedSourcePaths = options.files.resolvedPaths[fileType] || [];\n if (\n transformedSourcePaths.some(\n (sourcePath) => getRelative(sourcePath) === inputPath\n )\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nexport type BatchedFiles = {\n branchId: string;\n fileId: string;\n versionId: string;\n locale: string;\n outputPath: string;\n inputPath: string;\n}[];\n\nexport type DownloadFileBatchResult = {\n successful: BatchedFiles;\n failed: BatchedFiles;\n skipped: BatchedFiles;\n};\n/**\n * Downloads multiple translation files in a single batch request\n * @param fileTracker - Current translation status keyed by file identity\n * @param files - Array of files to download with their output paths\n * @param options - Resolved CLI settings used for merge and lockfile behavior\n * @param forceDownload - Whether to bypass an up-to-date local translation\n * @param inlineLibrary - Inline runtime used to label the shared GTJSON file\n * @returns Object containing successful and failed file IDs\n */\nexport async function downloadFileBatch(\n fileTracker: FileStatusTracker,\n files: BatchedFiles,\n options: Settings,\n forceDownload: boolean = false,\n inlineLibrary?: InlineLibrary\n): Promise<DownloadFileBatchResult> {\n // Local record of what version was last downloaded for each fileName:locale\n const {\n data: downloadedVersions,\n entryMap,\n originalV1,\n } = readLockfile(options);\n let didUpdateDownloadedLock = false;\n\n // Create a map of requested file keys to the file object\n const requestedFileMap = new Map(\n files.map((file) => [\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file,\n ])\n );\n const result: DownloadFileBatchResult = {\n successful: [],\n failed: [],\n skipped: [],\n };\n\n // Create a map of translationId to outputPath for easier lookup\n const outputPathMap = new Map(\n files.map((file) => [\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file.outputPath,\n ])\n );\n\n try {\n // Download the files\n const responseData = await api.downloadFileBatch(\n files.map((file) => ({\n fileId: file.fileId,\n branchId: file.branchId,\n versionId: file.versionId,\n locale: file.locale,\n }))\n );\n const downloadedFiles = responseData.files || [];\n\n // Process each file in the response\n for (const file of downloadedFiles) {\n const fileKey = `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`;\n const requestedFile = requestedFileMap.get(fileKey);\n if (!requestedFile) {\n continue;\n }\n try {\n const outputPath = outputPathMap.get(fileKey);\n const fileProperties = fileTracker.completed.get(fileKey);\n\n if (!outputPath || !fileProperties) {\n logger.warn(`No input/output path found for file: ${fileKey}`);\n recordWarning(\n 'failed_download',\n fileKey,\n 'No input/output path found'\n );\n result.failed.push(requestedFile);\n continue;\n }\n\n const {\n fileId,\n versionId,\n locale,\n branchId,\n fileName: inputPath,\n } = fileProperties;\n\n // Ensure the directory exists\n const dir = path.dirname(outputPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n // If a local translation already exists for the same source version, skip overwrite\n const existingEntry = entryMap.get(fileId);\n const downloadedTranslation =\n existingEntry?.versionId === versionId\n ? existingEntry.translations[locale]\n : undefined;\n const fileExists = fs.existsSync(outputPath);\n\n // Binary formats (e.g. LOTTIE zip bundles) carry base64 content that must\n // not go through the text merge/sort path — decode straight to bytes and\n // write. Skip only when an unchanged local translation already exists.\n if (isBinaryFileFormat(file.fileFormat)) {\n if (!forceDownload && fileExists && downloadedTranslation) {\n result.skipped.push(requestedFile);\n continue;\n }\n await fs.promises.writeFile(\n outputPath,\n Buffer.from(file.data, 'base64')\n );\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n fileFormat: file.fileFormat,\n inputPath,\n });\n result.successful.push(requestedFile);\n if (fileId && versionId && locale) {\n const entry = findOrCreateEntry(\n entryMap,\n downloadedVersions.entries,\n fileId,\n versionId\n );\n entry.fileName = inputPath;\n entry.translations[locale] = {\n updatedAt: new Date().toISOString(),\n // Store a relative path (matches the text path) so gt-lock.json\n // stays portable and the skip-on-re-download check matches.\n fileName: getRelative(outputPath),\n };\n // A staged entry tracks the whole file, not one locale. Keep it\n // staged until every configured locale has downloaded, so a partial\n // batch (locales still translating) doesn't abandon the rest.\n if (entry.staged) {\n entry.staged = !options.locales.every(\n (l) => entry.translations[l]\n );\n }\n didUpdateDownloadedLock = true;\n }\n continue;\n }\n\n // In-place translation files (composite schema JSON, .xcstrings\n // catalogs) merge translations into the source file itself, so\n // outputPath always exists and the lock can't tell whether this\n // locale's content or derived split outputs (e.g. {locale}/docs.json)\n // are still on disk. Always merge fresh API data so they are\n // regenerated every run; local edits to translated output are\n // preserved via `gt save-local`.\n const isXcstringsCatalog = file.fileFormat === 'XCSTRINGS';\n const isInPlaceComposite = options.options?.jsonSchema\n ? !!validateJsonSchema(options.options, inputPath)?.composite\n : false;\n const isInPlaceTranslationFile =\n isXcstringsCatalog || isInPlaceComposite;\n\n if (\n !forceDownload &&\n fileExists &&\n downloadedTranslation &&\n !isInPlaceTranslationFile\n ) {\n // For schema-based files, re-merge with current source in case\n // non-translatable fields changed (skip the API download, not the merge)\n try {\n let existingContent = fs.readFileSync(outputPath, 'utf8');\n // Resolve $ref before extraction if configured\n if (shouldResolveRefs(outputPath, options.options)) {\n try {\n const json = JSON.parse(existingContent);\n const { resolved } = resolveMintlifyRefs(json, outputPath);\n existingContent = JSON.stringify(resolved, null, 2);\n } catch {\n // Fall through with original content\n }\n }\n const jsonExtracted = options.options?.jsonSchema\n ? extractJson(\n existingContent,\n inputPath,\n options.options,\n locale,\n options.defaultLocale\n )\n : null;\n const extracted =\n jsonExtracted ??\n (options.options?.yamlSchema\n ? extractYaml(existingContent, inputPath, options.options)\n : null);\n if (extracted) {\n const remerged = mergeWithSource(\n extracted,\n locale,\n inputPath,\n options\n );\n let remergedData = remerged;\n if (outputPath.endsWith('.json')) {\n try {\n remergedData = sortJsonString(remergedData);\n } catch {\n // Fall through with unsorted content\n }\n }\n if (remergedData !== existingContent) {\n await fs.promises.writeFile(outputPath, remergedData);\n }\n // Track for postprocessing (e.g. openapi path localization)\n // even when the API download was skipped\n recordRemerged(outputPath);\n }\n } catch (error) {\n // If re-merge fails, still count as skipped — not worth failing\n // the download, but surface it so missing output is diagnosable\n logger.warn(\n `Failed to re-merge existing translation for ${outputPath} (${locale}): ${error}`\n );\n }\n // Even when the local copy is current, the served content may\n // still be missing review-withheld components — keep reporting\n reportWithheldGtJsonComponents(\n file.fileFormat,\n file.data,\n fileProperties.componentCount,\n locale,\n inlineLibrary\n );\n result.skipped.push(requestedFile);\n continue;\n }\n let data: string;\n if (isXcstringsCatalog) {\n // The pinned serializer owns the bytes and the JSON key sorter below\n // must never see them. JSON.parse hoists integer-like keys (\"404\")\n // first; versionId is unaffected (slices come from the parsed object)\n // and Xcode re-sorts on its next save, so the only effect is a\n // one-time reorder.\n data = mergeXcstringsLocale(file.data, locale, inputPath);\n } else {\n data = mergeWithSource(file.data, locale, inputPath, options);\n\n // Stable sort JSON keys for deterministic output\n if (file.fileFormat === 'GTJSON' || outputPath.endsWith('.json')) {\n try {\n data = sortJsonString(data);\n } catch (error) {\n logger.warn(`Failed to sort JSON file: ${file.id}: ` + error);\n }\n }\n }\n\n // Write the file to disk\n await fs.promises.writeFile(\n outputPath,\n encodeFileContent(data, file.fileFormat, inputPath, outputPath)\n );\n // Track as downloaded with metadata for downstream postprocessing\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n fileFormat: file.fileFormat,\n inputPath,\n });\n\n reportWithheldGtJsonComponents(\n file.fileFormat,\n data,\n fileProperties.componentCount,\n locale,\n inlineLibrary\n );\n\n result.successful.push(requestedFile);\n if (fileId && versionId && locale) {\n const entry = findOrCreateEntry(\n entryMap,\n downloadedVersions.entries,\n fileId,\n versionId\n );\n entry.fileName = inputPath;\n // Keep the hash upload recorded until postprocessing re-hashes the file\n entry.translations[locale] = {\n ...entry.translations[locale],\n updatedAt: new Date().toISOString(),\n fileName: getRelative(outputPath),\n };\n // A staged entry tracks the whole file, not one locale. Keep it\n // staged until every configured locale has downloaded, so a partial\n // batch (locales still translating) doesn't abandon the rest.\n if (entry.staged) {\n entry.staged = !options.locales.every((l) => entry.translations[l]);\n }\n didUpdateDownloadedLock = true;\n }\n } catch (error) {\n logger.error(`Error saving file ${fileKey}: ` + error);\n recordWarning(\n 'failed_download',\n fileKey,\n `Error saving file: ${error}`\n );\n result.failed.push(requestedFile);\n }\n }\n\n // Add any files that weren't in the response to the failed list\n const downloadedFileKeys = new Set(\n downloadedFiles.map(\n (file) =>\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`\n )\n );\n for (const [fileKey, requestedFile] of requestedFileMap.entries()) {\n if (!downloadedFileKeys.has(fileKey)) {\n result.failed.push(requestedFile);\n }\n }\n\n // Persist any updates to the downloaded map at the end of a successful cycle\n if (didUpdateDownloadedLock) {\n writeLockfile(downloadedVersions, originalV1);\n didUpdateDownloadedLock = false;\n }\n return result;\n } catch (error) {\n logger.error(\n `An unexpected error occurred while downloading files: ` + error\n );\n }\n\n // Mark all files as failed if we get here\n result.failed = [...requestedFileMap.values()];\n if (didUpdateDownloadedLock) {\n writeLockfile(downloadedVersions, originalV1);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAS,+BACP,YACA,eACA,gBACA,QACA,eACM;AACN,KAAI,eAAe,YAAY,kBAAkB,KAAM;CACvD,MAAM,WAAW,mBAAmB,cAAc;AAClD,KAAI,YAAY,KAAM;CACtB,MAAM,WAAW,iBAAiB;AAClC,KAAI,WAAW,EACb,eACE,kBACA,IAAI,uBAAuB,cAAc,CAAC,IAC1C,GAAG,SAAS,uCAAuC,OAAO,0CAC3D;;;;;;AAQL,SAAS,mBAAmB,SAAqC;AAC/D,KAAI;EACF,MAAM,SAAkB,KAAK,MAAM,QAAQ;AAC3C,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,CAChE;EAEF,MAAM,UACJ,UAAU,UACV,OAAO,SAAS,YAChB,UAAU,UACV,OAAO,QACP,OAAO,OAAO,SAAS,YACvB,CAAC,MAAM,QAAQ,OAAO,KAAK,GACvB,OAAO,OACP;AACN,SAAO,OAAO,KAAK,QAAQ,CAAC;SACtB;AACN;;;AAIJ,SAAS,eAAe,MAAsB;CAC5C,MAAM,aAAa,UAAU,KAAK,MAAM,KAAK,CAAC;AAC9C,QAAO,KAAK,UAAU,KAAK,MAAM,WAAW,EAAE,MAAM,EAAE;;;;;AAMxD,SAAS,gBACP,mBACA,QACA,WACA,SACQ;AACR,KAAI,4BAA4B,WAAW,QAAQ,CACjD,QAAO;AAET,KAAI,CAAC,QAAQ,QAAS,QAAO;CAE7B,MAAM,aAAa,QAAQ,QAAQ,aAC/B,mBAAmB,QAAQ,SAAS,UAAU,GAC9C;CACJ,MAAM,aACJ,CAAC,cAAc,QAAQ,QAAQ,aAC3B,mBAAmB,QAAQ,SAAS,UAAU,GAC9C;AAEN,KAAI,CA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KAAK,cAAc;AAKrC,MAAI,yBAAyB;AAC3B,iBAAc,oBAAoB,WAAW;AAC7C,6BAA0B;;AAE5B,SAAO;UACA,OAAO;AACd,SAAO,MACL,2DAA2D,MAC5D;;AAIH,QAAO,SAAS,CAAC,GAAG,iBAAiB,QAAQ,CAAC;AAC9C,KAAI,wBACF,eAAc,oBAAoB,WAAW;AAE/C,QAAO"}
|
|
1
|
+
{"version":3,"file":"downloadFileBatch.js","names":["fs","path"],"sources":["../../src/api/downloadFileBatch.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { isBinaryFileFormat } from 'generaltranslation/types';\nimport { logger } from '../console/logger.js';\nimport { api } from '../utils/api.js';\nimport { Settings } from '../types/index.js';\nimport { validateJsonSchema } from '../formats/json/utils.js';\nimport { validateYamlSchema } from '../formats/yaml/utils.js';\nimport { mergeJson } from '../formats/json/mergeJson.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport { mergeXcstringsLocale } from '../formats/xcstrings/mergeXcstrings.js';\nimport mergeYaml from '../formats/yaml/mergeYaml.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n} from '../utils/resolveMintlifyRefs.js';\nimport {\n readLockfile,\n writeLockfile,\n findOrCreateEntry,\n} from '../fs/config/downloadedVersions.js';\nimport { recordDownloaded, recordRemerged } from '../state/recentDownloads.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport type { FileStatusTracker } from '../workflows/steps/PollJobsStep.js';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport { hasNonIdentityFileFormatTransformForType } from '../formats/files/transformFormat.js';\nimport { getRelative } from '../fs/findFilepath.js';\nimport { encodeFileContent } from '../fs/fileContent.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../types/libraries.js';\n\n/**\n * The platform withholds unapproved review-gated GTJSON components from\n * served output. Reports the delta between the source component count and\n * the served content so partially-served files don't read as fully\n * translated — for both fresh downloads and already-downloaded skips.\n */\nfunction reportWithheldGtJsonComponents(\n fileFormat: string | undefined,\n servedContent: string,\n componentCount: number | undefined,\n locale: string,\n inlineLibrary?: InlineLibrary\n): void {\n if (fileFormat !== 'GTJSON' || componentCount == null) return;\n const received = countGtJsonEntries(servedContent);\n if (received == null) return;\n const withheld = componentCount - received;\n if (withheld > 0) {\n recordWarning(\n 'pending_review',\n `<${getInlineElementsLabel(inlineLibrary)}>`,\n `${withheld} component translation(s) for locale ${locale} require review and are not approved yet`\n );\n }\n}\n\n/**\n * Counts entries in downloaded GTJSON output, tolerating both the flat\n * public shape and a wrapped { type, data } shape.\n */\nfunction countGtJsonEntries(content: string): number | undefined {\n try {\n const parsed: unknown = JSON.parse(content);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n const entries =\n 'type' in parsed &&\n parsed.type === 'GTJSON' &&\n 'data' in parsed &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ? parsed.data\n : parsed;\n return Object.keys(entries).length;\n } catch {\n return undefined;\n }\n}\n\nfunction sortJsonString(data: string): string {\n return JSON.stringify(JSON.parse(data), sortKeys, 2);\n}\n\nfunction sortKeys(_key: string, value: unknown): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n );\n}\n\n/**\n * Merges translated content with the current source file for schema-based formats.\n */\nfunction mergeWithSource(\n translatedContent: string,\n locale: string,\n inputPath: string,\n options: Settings\n): string {\n if (shouldSkipSourceFormatMerge(inputPath, options)) {\n return translatedContent;\n }\n if (!options.options) return translatedContent;\n\n const jsonSchema = options.options.jsonSchema\n ? validateJsonSchema(options.options, inputPath)\n : null;\n const yamlSchema =\n !jsonSchema && options.options.yamlSchema\n ? validateYamlSchema(options.options, inputPath)\n : null;\n\n if (!jsonSchema && !yamlSchema) return translatedContent;\n\n const sourceContent = fs.readFileSync(inputPath, 'utf8');\n if (!sourceContent) return translatedContent;\n\n if (jsonSchema) {\n // Resolve $ref before merging if configured\n let resolvedSourceContent = sourceContent;\n if (shouldResolveRefs(inputPath, options.options)) {\n try {\n const json = JSON.parse(sourceContent);\n const { resolved } = resolveMintlifyRefs(json, inputPath);\n resolvedSourceContent = JSON.stringify(resolved, null, 2);\n } catch {\n // Fall through with original content\n }\n }\n return mergeJson(\n resolvedSourceContent,\n inputPath,\n options.options,\n [{ translatedContent, targetLocale: locale }],\n options.defaultLocale,\n options.locales\n )[0];\n } else {\n return mergeYaml(\n sourceContent,\n inputPath,\n options.options,\n [{ translatedContent, targetLocale: locale }],\n options.defaultLocale\n )[0];\n }\n}\n\n/**\n * Determines whether a source file should be skipped for schema re-merging.\n * @param inputPath - The path of the source file\n * @param options - The settings for the project\n * @returns True if the source file should be skipped for schema re-merging, false otherwise\n */\nfunction shouldSkipSourceFormatMerge(\n inputPath: string,\n options: Settings\n): boolean {\n for (const fileType of SUPPORTED_FILE_EXTENSIONS) {\n if (!hasNonIdentityFileFormatTransformForType(options, fileType)) continue;\n\n const transformedSourcePaths = options.files.resolvedPaths[fileType] || [];\n if (\n transformedSourcePaths.some(\n (sourcePath) => getRelative(sourcePath) === inputPath\n )\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nexport type BatchedFiles = {\n branchId: string;\n fileId: string;\n versionId: string;\n locale: string;\n outputPath: string;\n inputPath: string;\n}[];\n\nexport type DownloadFileBatchResult = {\n successful: BatchedFiles;\n failed: BatchedFiles;\n skipped: BatchedFiles;\n};\n/**\n * Downloads multiple translation files in a single batch request\n * @param fileTracker - Current translation status keyed by file identity\n * @param files - Array of files to download with their output paths\n * @param options - Resolved CLI settings used for merge and lockfile behavior\n * @param forceDownload - Whether to bypass an up-to-date local translation\n * @param inlineLibrary - Inline runtime used to label the shared GTJSON file\n * @returns Object containing successful and failed file IDs\n */\nexport async function downloadFileBatch(\n fileTracker: FileStatusTracker,\n files: BatchedFiles,\n options: Settings,\n forceDownload: boolean = false,\n inlineLibrary?: InlineLibrary\n): Promise<DownloadFileBatchResult> {\n // Local record of what version was last downloaded for each fileName:locale\n const {\n data: downloadedVersions,\n entryMap,\n originalV1,\n } = readLockfile(options);\n let didUpdateDownloadedLock = false;\n\n // Create a map of requested file keys to the file object\n const requestedFileMap = new Map(\n files.map((file) => [\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file,\n ])\n );\n const result: DownloadFileBatchResult = {\n successful: [],\n failed: [],\n skipped: [],\n };\n\n // Create a map of translationId to outputPath for easier lookup\n const outputPathMap = new Map(\n files.map((file) => [\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file.outputPath,\n ])\n );\n\n try {\n // Download the files\n const responseData = await api.downloadFileBatch(\n files.map((file) => ({\n fileId: file.fileId,\n branchId: file.branchId,\n versionId: file.versionId,\n locale: file.locale,\n }))\n );\n const downloadedFiles = responseData.files || [];\n\n // Process each file in the response\n for (const file of downloadedFiles) {\n const fileKey = `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`;\n const requestedFile = requestedFileMap.get(fileKey);\n if (!requestedFile) {\n continue;\n }\n try {\n const outputPath = outputPathMap.get(fileKey);\n const fileProperties = fileTracker.completed.get(fileKey);\n\n if (!outputPath || !fileProperties) {\n logger.warn(`No input/output path found for file: ${fileKey}`);\n recordWarning(\n 'failed_download',\n fileKey,\n 'No input/output path found'\n );\n result.failed.push(requestedFile);\n continue;\n }\n\n const {\n fileId,\n versionId,\n locale,\n branchId,\n fileName: inputPath,\n } = fileProperties;\n\n // Ensure the directory exists\n const dir = path.dirname(outputPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n // If a local translation already exists for the same source version, skip overwrite\n const existingEntry = entryMap.get(fileId);\n const downloadedTranslation =\n existingEntry?.versionId === versionId\n ? existingEntry.translations[locale]\n : undefined;\n const fileExists = fs.existsSync(outputPath);\n\n // Binary formats (e.g. LOTTIE zip bundles) carry base64 content that must\n // not go through the text merge/sort path — decode straight to bytes and\n // write. Skip only when an unchanged local translation already exists.\n if (isBinaryFileFormat(file.fileFormat)) {\n if (!forceDownload && fileExists && downloadedTranslation) {\n result.skipped.push(requestedFile);\n continue;\n }\n await fs.promises.writeFile(\n outputPath,\n Buffer.from(file.data, 'base64')\n );\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n fileFormat: file.fileFormat,\n inputPath,\n });\n result.successful.push(requestedFile);\n if (fileId && versionId && locale) {\n const entry = findOrCreateEntry(\n entryMap,\n downloadedVersions.entries,\n fileId,\n versionId\n );\n entry.fileName = inputPath;\n entry.translations[locale] = {\n updatedAt: new Date().toISOString(),\n // Store a relative path (matches the text path) so gt-lock.json\n // stays portable and the skip-on-re-download check matches.\n fileName: getRelative(outputPath),\n };\n // A staged entry tracks the whole file, not one locale. Keep it\n // staged until every configured locale has downloaded, so a partial\n // batch (locales still translating) doesn't abandon the rest.\n if (entry.staged) {\n entry.staged = !options.locales.every(\n (l) => entry.translations[l]\n );\n }\n didUpdateDownloadedLock = true;\n }\n continue;\n }\n\n // In-place translation files (composite schema JSON, .xcstrings\n // catalogs) merge translations into the source file itself, so\n // outputPath always exists and the lock can't tell whether this\n // locale's content or derived split outputs (e.g. {locale}/docs.json)\n // are still on disk. Always merge fresh API data so they are\n // regenerated every run; local edits to translated output are\n // preserved via `gt save-local`.\n const isXcstringsCatalog = file.fileFormat === 'XCSTRINGS';\n const isInPlaceComposite = options.options?.jsonSchema\n ? !!validateJsonSchema(options.options, inputPath)?.composite\n : false;\n const isInPlaceTranslationFile =\n isXcstringsCatalog || isInPlaceComposite;\n\n if (\n !forceDownload &&\n fileExists &&\n downloadedTranslation &&\n !isInPlaceTranslationFile\n ) {\n // For schema-based files, re-merge with current source in case\n // non-translatable fields changed (skip the API download, not the merge)\n try {\n let existingContent = fs.readFileSync(outputPath, 'utf8');\n // Resolve $ref before extraction if configured\n if (shouldResolveRefs(outputPath, options.options)) {\n try {\n const json = JSON.parse(existingContent);\n const { resolved } = resolveMintlifyRefs(json, outputPath);\n existingContent = JSON.stringify(resolved, null, 2);\n } catch {\n // Fall through with original content\n }\n }\n const jsonExtracted = options.options?.jsonSchema\n ? extractJson(\n existingContent,\n inputPath,\n options.options,\n locale,\n options.defaultLocale\n )\n : null;\n const extracted =\n jsonExtracted ??\n (options.options?.yamlSchema\n ? extractYaml(existingContent, inputPath, options.options)\n : null);\n if (extracted) {\n const remerged = mergeWithSource(\n extracted,\n locale,\n inputPath,\n options\n );\n if (remerged !== existingContent) {\n await fs.promises.writeFile(outputPath, remerged);\n }\n // Track for postprocessing (e.g. openapi path localization)\n // even when the API download was skipped\n recordRemerged(outputPath);\n }\n } catch (error) {\n // If re-merge fails, still count as skipped — not worth failing\n // the download, but surface it so missing output is diagnosable\n logger.warn(\n `Failed to re-merge existing translation for ${outputPath} (${locale}): ${error}`\n );\n }\n // Even when the local copy is current, the served content may\n // still be missing review-withheld components — keep reporting\n reportWithheldGtJsonComponents(\n file.fileFormat,\n file.data,\n fileProperties.componentCount,\n locale,\n inlineLibrary\n );\n result.skipped.push(requestedFile);\n continue;\n }\n let data: string;\n if (isXcstringsCatalog) {\n // The pinned serializer owns the bytes and the JSON key sorter below\n // must never see them. JSON.parse hoists integer-like keys (\"404\")\n // first; versionId is unaffected (slices come from the parsed object)\n // and Xcode re-sorts on its next save, so the only effect is a\n // one-time reorder.\n data = mergeXcstringsLocale(file.data, locale, inputPath);\n } else {\n data = mergeWithSource(file.data, locale, inputPath, options);\n\n // Sort GTJSON keys for stable diffs\n if (file.fileFormat === 'GTJSON') {\n try {\n data = sortJsonString(data);\n } catch (error) {\n logger.warn(`Failed to sort JSON file: ${file.id}: ` + error);\n }\n }\n }\n\n // Write the file to disk\n await fs.promises.writeFile(\n outputPath,\n encodeFileContent(data, file.fileFormat, inputPath, outputPath)\n );\n // Track as downloaded with metadata for downstream postprocessing\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n fileFormat: file.fileFormat,\n inputPath,\n });\n\n reportWithheldGtJsonComponents(\n file.fileFormat,\n data,\n fileProperties.componentCount,\n locale,\n inlineLibrary\n );\n\n result.successful.push(requestedFile);\n if (fileId && versionId && locale) {\n const entry = findOrCreateEntry(\n entryMap,\n downloadedVersions.entries,\n fileId,\n versionId\n );\n entry.fileName = inputPath;\n // Keep the hash upload recorded until postprocessing re-hashes the file\n entry.translations[locale] = {\n ...entry.translations[locale],\n updatedAt: new Date().toISOString(),\n fileName: getRelative(outputPath),\n };\n // A staged entry tracks the whole file, not one locale. Keep it\n // staged until every configured locale has downloaded, so a partial\n // batch (locales still translating) doesn't abandon the rest.\n if (entry.staged) {\n entry.staged = !options.locales.every((l) => entry.translations[l]);\n }\n didUpdateDownloadedLock = true;\n }\n } catch (error) {\n logger.error(`Error saving file ${fileKey}: ` + error);\n recordWarning(\n 'failed_download',\n fileKey,\n `Error saving file: ${error}`\n );\n result.failed.push(requestedFile);\n }\n }\n\n // Add any files that weren't in the response to the failed list\n const downloadedFileKeys = new Set(\n downloadedFiles.map(\n (file) =>\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`\n )\n );\n for (const [fileKey, requestedFile] of requestedFileMap.entries()) {\n if (!downloadedFileKeys.has(fileKey)) {\n result.failed.push(requestedFile);\n }\n }\n\n // Persist any updates to the downloaded map at the end of a successful cycle\n if (didUpdateDownloadedLock) {\n writeLockfile(downloadedVersions, originalV1);\n didUpdateDownloadedLock = false;\n }\n return result;\n } catch (error) {\n logger.error(\n `An unexpected error occurred while downloading files: ` + error\n );\n }\n\n // Mark all files as failed if we get here\n result.failed = [...requestedFileMap.values()];\n if (didUpdateDownloadedLock) {\n writeLockfile(downloadedVersions, originalV1);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,+BACP,YACA,eACA,gBACA,QACA,eACM;AACN,KAAI,eAAe,YAAY,kBA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Q,CAAC;AAC9C,KAAI,wBACF,eAAc,oBAAoB,WAAW;AAE/C,QAAO"}
|
package/dist/bin/bin-entry.js
CHANGED
package/dist/cli/base.js
CHANGED
|
@@ -15,10 +15,11 @@ import { resolveConfig } from "../config/resolveConfig.js";
|
|
|
15
15
|
import { api } from "../utils/api.js";
|
|
16
16
|
import { generateSettings } from "../config/generateSettings.js";
|
|
17
17
|
import { applySetupConfig, mergeSetupConfig } from "../fs/config/setupConfig.js";
|
|
18
|
+
import { areCredentialsSet, getDevelopmentEnvNames, inspectCredentialsEnvFile } from "../utils/credentials.js";
|
|
19
|
+
import { warnReactPackageCompatibility } from "../utils/reactPackageCompatibility.js";
|
|
18
20
|
import { getBuildToolSetup } from "../setup/buildTools/index.js";
|
|
19
21
|
import { executeReactSetup, resolveReactSetup } from "../setup/wizard.js";
|
|
20
22
|
import { getDesiredLocales } from "../setup/userInput.js";
|
|
21
|
-
import { areCredentialsSet, getDevelopmentEnvNames, inspectCredentialsEnvFile } from "../utils/credentials.js";
|
|
22
23
|
import { loginInteractively } from "../auth/interactiveLogin.js";
|
|
23
24
|
import { INIT_SOURCE_HELP, OnboardingError, asRecord, attachConfigureFlags, attachInitFlags, describeDefaults, displaySetupHeader, getConfiguredFramework, installWithProgress, parseFilePatterns, readSetupConfig, reportJsonExitsBeforeOnboarding, resolvePackageManager, runOnboarding, setupConfigPath, validateSetupPattern } from "../setup/onboarding.js";
|
|
24
25
|
import { checkDevelopmentProjectInputs, productionRuntimeKeyGuidance, provisionDevelopmentCredentials, resolveDevelopmentProject, signInForSetup } from "../setup/developmentCredentials.js";
|
|
@@ -45,7 +46,6 @@ import { splitMintlifyLanguageRefs } from "../utils/splitMintlifyLanguageRefs.js
|
|
|
45
46
|
import { localizeMintlifyRedirects } from "../formats/files/postprocess/localizeMintlifyRedirects.js";
|
|
46
47
|
import { runMergeDriver } from "../git/mergeDrivers.js";
|
|
47
48
|
import { setupGitMergeDrivers } from "../git/setupMergeDrivers.js";
|
|
48
|
-
import { warnReactPackageCompatibility } from "../utils/reactPackageCompatibility.js";
|
|
49
49
|
import { handleApiCommand } from "./commands/api.js";
|
|
50
50
|
import chalk from "chalk";
|
|
51
51
|
import path from "node:path";
|
|
@@ -705,11 +705,13 @@ See https://www.npmjs.com/package/gt-vue`);
|
|
|
705
705
|
translationsDir
|
|
706
706
|
});
|
|
707
707
|
if (guidance) logger.message(guidance);
|
|
708
|
-
} else if (storage === "cdn" && buildTool && !reactSetup && configuredTranslationsDir !== void 0)
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
708
|
+
} else if (storage === "cdn" && buildTool && !reactSetup && configuredTranslationsDir !== void 0) {
|
|
709
|
+
const action = await buildTool.getCDNStorageAction?.(buildToolContext);
|
|
710
|
+
if (action !== null) reportManualAction(action ?? {
|
|
711
|
+
whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,
|
|
712
|
+
fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`
|
|
713
|
+
});
|
|
714
|
+
} else if (storage === "cdn" && !buildTool && configuredTranslationsDir !== void 0) {
|
|
713
715
|
const loaders = findLoadTranslationsFiles(cwd).map((loader) => path.relative(cwd, loader));
|
|
714
716
|
if (loaders.length > 0) {
|
|
715
717
|
const loaderFiles = loaders.join(", ");
|