gt 2.14.55 → 2.14.56
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 +6 -0
- package/dist/api/downloadFileBatch.js +1 -1
- package/dist/api/downloadFileBatch.js.map +1 -1
- package/dist/formats/files/fileMapping.js +4 -1
- package/dist/formats/files/fileMapping.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/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.14.56
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#1724](https://github.com/generaltranslation/gt/pull/1724) [`dd0d1cd`](https://github.com/generaltranslation/gt/commit/dd0d1cd0276cd0a158fc3dd73a312502066782a7) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Fix translation file path in `gt-lock.json`
|
|
8
|
+
|
|
3
9
|
## 2.14.55
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
@@ -147,7 +147,7 @@ async function downloadFileBatch(fileTracker, files, options, forceDownload = fa
|
|
|
147
147
|
entry.staged = false;
|
|
148
148
|
entry.translations[locale] = {
|
|
149
149
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
150
|
-
fileName: outputPath
|
|
150
|
+
fileName: getRelative(outputPath)
|
|
151
151
|
};
|
|
152
152
|
didUpdateDownloadedLock = true;
|
|
153
153
|
}
|
|
@@ -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 { logger } from '../console/logger.js';\nimport { gt } from '../utils/gt.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 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';\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 files - Array of files to download with their output paths\n * @param maxRetries - Maximum number of retry attempts\n * @param retryDelay - Delay between retries in milliseconds\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): 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 gt.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 // Composite schema files merge translations into the source file itself,\n // so outputPath always exists and the lock can't tell whether derived\n // split outputs (e.g. {locale}/docs.json) are still on disk. Always\n // merge fresh API data so derived files are regenerated every run;\n // local edits to translated output are preserved via `gt save-local`.\n const isInPlaceComposite = options.options?.jsonSchema\n ? !!validateJsonSchema(options.options, inputPath)?.composite\n : false;\n\n if (\n !forceDownload &&\n fileExists &&\n downloadedTranslation &&\n !isInPlaceComposite\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 result.skipped.push(requestedFile);\n continue;\n }\n let 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 // Write the file to disk\n await fs.promises.writeFile(outputPath, data);\n // Track as downloaded with metadata for downstream postprocessing\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n inputPath,\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 entry.staged = false;\n entry.translations[locale] = {\n updatedAt: new Date().toISOString(),\n fileName: outputPath,\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":";;;;;;;;;;;;;;;;;;;AA4BA,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,CAAC,cAAc,CAAC,WAAY,QAAO;CAEvC,MAAM,gBAAgBA,KAAG,aAAa,WAAW,OAAO;AACxD,KAAI,CAAC,cAAe,QAAO;AAE3B,KAAI,YAAY;EAEd,IAAI,w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,OAAK,MAAM,CAAC,SAAS,kBAAkB,iBAAiB,SAAS,CAC/D,KAAI,CAAC,mBAAmB,IAAI,QAAQ,CAClC,QAAO,OAAO,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 { logger } from '../console/logger.js';\nimport { gt } from '../utils/gt.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 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';\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 files - Array of files to download with their output paths\n * @param maxRetries - Maximum number of retry attempts\n * @param retryDelay - Delay between retries in milliseconds\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): 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 gt.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 // Composite schema files merge translations into the source file itself,\n // so outputPath always exists and the lock can't tell whether derived\n // split outputs (e.g. {locale}/docs.json) are still on disk. Always\n // merge fresh API data so derived files are regenerated every run;\n // local edits to translated output are preserved via `gt save-local`.\n const isInPlaceComposite = options.options?.jsonSchema\n ? !!validateJsonSchema(options.options, inputPath)?.composite\n : false;\n\n if (\n !forceDownload &&\n fileExists &&\n downloadedTranslation &&\n !isInPlaceComposite\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 result.skipped.push(requestedFile);\n continue;\n }\n let 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 // Write the file to disk\n await fs.promises.writeFile(outputPath, data);\n // Track as downloaded with metadata for downstream postprocessing\n recordDownloaded(outputPath, {\n branchId,\n fileId,\n versionId,\n locale,\n inputPath,\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 entry.staged = false;\n entry.translations[locale] = {\n updatedAt: new Date().toISOString(),\n fileName: getRelative(outputPath),\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":";;;;;;;;;;;;;;;;;;;AA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YAAY,KAAK;AAE7C,qBAAiB,YAAY;KAC3B;KACA;KACA;KACA;KACA;KACD,CAAC;AAEF,WAAO,WAAW,KAAK,cAAc;AACrC,QAAI,UAAU,aAAa,QAAQ;KACjC,MAAM,QAAQ,kBACZ,UACA,mBAAmB,SACnB,QACA,UACD;AACD,WAAM,WAAW;AACjB,WAAM,SAAS;AACf,WAAM,aAAa,UAAU;MAC3B,4BAAW,IAAI,MAAM,EAAC,aAAa;MACnC,UAAU,YAAY,WAAW;MAClC;AACD,+BAA0B;;YAErB,OAAO;AACd,WAAO,MAAM,qBAAqB,QAAQ,MAAM,MAAM;AACtD,kBACE,mBACA,SACA,sBAAsB,QACvB;AACD,WAAO,OAAO,KAAK,cAAc;;;EAKrC,MAAM,qBAAqB,IAAI,IAC7B,gBAAgB,KACb,SACC,GAAG,KAAK,SAAS,GAAG,KAAK,OAAO,GAAG,KAAK,UAAU,GAAG,KAAK,SAC7D,CACF;AACD,OAAK,MAAM,CAAC,SAAS,kBAAkB,iBAAiB,SAAS,CAC/D,KAAI,CAAC,mBAAmB,IAAI,QAAQ,CAClC,QAAO,OAAO,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"}
|
|
@@ -21,7 +21,10 @@ function createFileMapping(filePaths, placeholderPaths, transformPaths, transfor
|
|
|
21
21
|
for (const locale of targetLocales) {
|
|
22
22
|
const translatedPaths = resolveLocaleFiles(placeholderPaths, locale);
|
|
23
23
|
const localeMapping = {};
|
|
24
|
-
if (translatedPaths.gt)
|
|
24
|
+
if (translatedPaths.gt) {
|
|
25
|
+
const filepath = translatedPaths.gt;
|
|
26
|
+
localeMapping[TEMPLATE_FILE_NAME] = getRelative(filepath);
|
|
27
|
+
}
|
|
25
28
|
for (const typeIndex of SUPPORTED_FILE_EXTENSIONS) {
|
|
26
29
|
if (!filePaths[typeIndex] || !translatedPaths[typeIndex]) continue;
|
|
27
30
|
const sourcePaths = filePaths[typeIndex];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileMapping.js","names":[],"sources":["../../../src/formats/files/fileMapping.ts"],"sourcesContent":["import {\n ResolvedFiles,\n TransformFiles,\n TransformFormats,\n} from '../../types/index.js';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../files/supportedFiles.js';\nimport { resolveLocaleFiles } from '../../fs/config/parseFilesConfig.js';\nimport path from 'node:path';\nimport { getRelative } from '../../fs/findFilepath.js';\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport { replaceLocalePlaceholders } from '../utils.js';\nimport { FileMapping } from '../../types/files.js';\nimport { TEMPLATE_FILE_NAME } from '../../utils/constants.js';\nimport { replaceFileExtensionForFormat } from './transformFormat.js';\n\n/**\n * Creates a mapping between source files and their translated counterparts for each locale\n * @param filePaths - Resolved file paths for different file types\n * @param placeholderPaths - Placeholder paths for translated files\n * @param transformPaths - Transform paths for file naming\n * @param transformFormats - Output file format transforms for translated files\n * @param locales - List of locales to create a mapping for\n * @returns A mapping between source files and their translated counterparts for each locale, in the form of relative paths\n */\nexport function createFileMapping(\n filePaths: ResolvedFiles,\n placeholderPaths: ResolvedFiles,\n transformPaths: TransformFiles,\n transformFormats: TransformFormats,\n targetLocales: string[],\n defaultLocale: string\n): FileMapping {\n const fileMapping: FileMapping = {};\n\n for (const locale of targetLocales) {\n const translatedPaths = resolveLocaleFiles(placeholderPaths, locale);\n const localeMapping: FileMapping[string] = {};\n\n // Process each file type\n\n // Start with GTJSON Template files\n if (translatedPaths.gt) {\n const filepath = translatedPaths.gt;\n localeMapping[TEMPLATE_FILE_NAME] = filepath;\n }\n\n for (const typeIndex of SUPPORTED_FILE_EXTENSIONS) {\n if (!filePaths[typeIndex] || !translatedPaths[typeIndex]) continue;\n\n const sourcePaths = filePaths[typeIndex];\n let translatedFiles = translatedPaths[typeIndex];\n if (!translatedFiles) continue;\n\n const transformPath = transformPaths[typeIndex];\n const transformFormat = transformFormats?.[typeIndex];\n\n if (transformPath) {\n if (typeof transformPath === 'string') {\n translatedFiles = translatedFiles.map((filePath) => {\n const directory = path.dirname(filePath);\n const fileName = path.basename(filePath);\n const baseName = fileName.split('.')[0];\n const transformedFileName = transformPath\n .replace('*', baseName)\n .replace('[locale]', locale);\n return path.join(directory, transformedFileName);\n });\n } else if (Array.isArray(transformPath)) {\n // transformPath is an array of TransformOption objects\n const targetLocaleProperties = getLocaleProperties(locale);\n const defaultLocaleProperties = getLocaleProperties(defaultLocale);\n\n translatedFiles = translatedFiles.map((filePath) => {\n const relativePath = getRelative(filePath);\n\n // Try each transform in order until one matches\n for (const transform of transformPath) {\n if (!transform.replace || typeof transform.replace !== 'string') {\n continue;\n }\n\n // Replace all locale property placeholders in the replace string\n const replaceString = replaceLocalePlaceholders(\n transform.replace,\n targetLocaleProperties\n );\n\n if (transform.match && typeof transform.match === 'string') {\n // Replace locale placeholders in the match string using defaultLocale properties\n let matchString = transform.match;\n matchString = replaceLocalePlaceholders(\n matchString,\n defaultLocaleProperties\n );\n\n const regex = new RegExp(matchString);\n if (regex.test(relativePath)) {\n // This transform matches, apply it and break\n const transformedPath = relativePath.replace(\n new RegExp(matchString, 'g'),\n replaceString\n );\n return path.resolve(transformedPath);\n }\n } else {\n // No match provided: treat as a direct replacement (override)\n return path.resolve(replaceString);\n }\n }\n\n // If no transforms matched, return the original path\n return filePath;\n });\n } else {\n // transformPath is an object\n const targetLocaleProperties = getLocaleProperties(locale);\n const defaultLocaleProperties = getLocaleProperties(defaultLocale);\n if (\n !transformPath.replace ||\n typeof transformPath.replace !== 'string'\n ) {\n continue;\n }\n // Replace all locale property placeholders\n const replaceString = replaceLocalePlaceholders(\n transformPath.replace,\n targetLocaleProperties\n );\n translatedFiles = translatedFiles.map((filePath) => {\n let relativePath = getRelative(filePath);\n if (\n transformPath.match &&\n typeof transformPath.match === 'string'\n ) {\n // Replace locale placeholders in the match string using defaultLocale properties\n let matchString = transformPath.match;\n matchString = replaceLocalePlaceholders(\n matchString,\n defaultLocaleProperties\n );\n\n relativePath = relativePath.replace(\n new RegExp(matchString, 'g'),\n replaceString\n );\n } else {\n relativePath = replaceString;\n }\n return path.resolve(relativePath);\n });\n }\n }\n\n for (let i = 0; i < sourcePaths.length; i++) {\n const sourceFile = getRelative(sourcePaths[i]);\n // Format transforms keep the mapped path but rewrite the output suffix.\n const translatedFile = getRelative(\n transformFormat\n ? replaceFileExtensionForFormat(translatedFiles[i], transformFormat)\n : translatedFiles[i]\n );\n localeMapping[sourceFile] = translatedFile;\n }\n }\n\n fileMapping[locale] = localeMapping;\n }\n\n return fileMapping;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,SAAgB,kBACd,WACA,kBACA,gBACA,kBACA,eACA,eACa;CACb,MAAM,cAA2B,EAAE;AAEnC,MAAK,MAAM,UAAU,eAAe;EAClC,MAAM,kBAAkB,mBAAmB,kBAAkB,OAAO;EACpE,MAAM,gBAAqC,EAAE;AAK7C,MAAI,gBAAgB,
|
|
1
|
+
{"version":3,"file":"fileMapping.js","names":[],"sources":["../../../src/formats/files/fileMapping.ts"],"sourcesContent":["import {\n ResolvedFiles,\n TransformFiles,\n TransformFormats,\n} from '../../types/index.js';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../files/supportedFiles.js';\nimport { resolveLocaleFiles } from '../../fs/config/parseFilesConfig.js';\nimport path from 'node:path';\nimport { getRelative } from '../../fs/findFilepath.js';\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport { replaceLocalePlaceholders } from '../utils.js';\nimport { FileMapping } from '../../types/files.js';\nimport { TEMPLATE_FILE_NAME } from '../../utils/constants.js';\nimport { replaceFileExtensionForFormat } from './transformFormat.js';\n\n/**\n * Creates a mapping between source files and their translated counterparts for each locale\n * @param filePaths - Resolved file paths for different file types\n * @param placeholderPaths - Placeholder paths for translated files\n * @param transformPaths - Transform paths for file naming\n * @param transformFormats - Output file format transforms for translated files\n * @param locales - List of locales to create a mapping for\n * @returns A mapping between source files and their translated counterparts for each locale, in the form of relative paths\n */\nexport function createFileMapping(\n filePaths: ResolvedFiles,\n placeholderPaths: ResolvedFiles,\n transformPaths: TransformFiles,\n transformFormats: TransformFormats,\n targetLocales: string[],\n defaultLocale: string\n): FileMapping {\n const fileMapping: FileMapping = {};\n\n for (const locale of targetLocales) {\n const translatedPaths = resolveLocaleFiles(placeholderPaths, locale);\n const localeMapping: FileMapping[string] = {};\n\n // Process each file type\n\n // Start with GTJSON Template files\n if (translatedPaths.gt) {\n const filepath = translatedPaths.gt;\n localeMapping[TEMPLATE_FILE_NAME] = getRelative(filepath);\n }\n\n for (const typeIndex of SUPPORTED_FILE_EXTENSIONS) {\n if (!filePaths[typeIndex] || !translatedPaths[typeIndex]) continue;\n\n const sourcePaths = filePaths[typeIndex];\n let translatedFiles = translatedPaths[typeIndex];\n if (!translatedFiles) continue;\n\n const transformPath = transformPaths[typeIndex];\n const transformFormat = transformFormats?.[typeIndex];\n\n if (transformPath) {\n if (typeof transformPath === 'string') {\n translatedFiles = translatedFiles.map((filePath) => {\n const directory = path.dirname(filePath);\n const fileName = path.basename(filePath);\n const baseName = fileName.split('.')[0];\n const transformedFileName = transformPath\n .replace('*', baseName)\n .replace('[locale]', locale);\n return path.join(directory, transformedFileName);\n });\n } else if (Array.isArray(transformPath)) {\n // transformPath is an array of TransformOption objects\n const targetLocaleProperties = getLocaleProperties(locale);\n const defaultLocaleProperties = getLocaleProperties(defaultLocale);\n\n translatedFiles = translatedFiles.map((filePath) => {\n const relativePath = getRelative(filePath);\n\n // Try each transform in order until one matches\n for (const transform of transformPath) {\n if (!transform.replace || typeof transform.replace !== 'string') {\n continue;\n }\n\n // Replace all locale property placeholders in the replace string\n const replaceString = replaceLocalePlaceholders(\n transform.replace,\n targetLocaleProperties\n );\n\n if (transform.match && typeof transform.match === 'string') {\n // Replace locale placeholders in the match string using defaultLocale properties\n let matchString = transform.match;\n matchString = replaceLocalePlaceholders(\n matchString,\n defaultLocaleProperties\n );\n\n const regex = new RegExp(matchString);\n if (regex.test(relativePath)) {\n // This transform matches, apply it and break\n const transformedPath = relativePath.replace(\n new RegExp(matchString, 'g'),\n replaceString\n );\n return path.resolve(transformedPath);\n }\n } else {\n // No match provided: treat as a direct replacement (override)\n return path.resolve(replaceString);\n }\n }\n\n // If no transforms matched, return the original path\n return filePath;\n });\n } else {\n // transformPath is an object\n const targetLocaleProperties = getLocaleProperties(locale);\n const defaultLocaleProperties = getLocaleProperties(defaultLocale);\n if (\n !transformPath.replace ||\n typeof transformPath.replace !== 'string'\n ) {\n continue;\n }\n // Replace all locale property placeholders\n const replaceString = replaceLocalePlaceholders(\n transformPath.replace,\n targetLocaleProperties\n );\n translatedFiles = translatedFiles.map((filePath) => {\n let relativePath = getRelative(filePath);\n if (\n transformPath.match &&\n typeof transformPath.match === 'string'\n ) {\n // Replace locale placeholders in the match string using defaultLocale properties\n let matchString = transformPath.match;\n matchString = replaceLocalePlaceholders(\n matchString,\n defaultLocaleProperties\n );\n\n relativePath = relativePath.replace(\n new RegExp(matchString, 'g'),\n replaceString\n );\n } else {\n relativePath = replaceString;\n }\n return path.resolve(relativePath);\n });\n }\n }\n\n for (let i = 0; i < sourcePaths.length; i++) {\n const sourceFile = getRelative(sourcePaths[i]);\n // Format transforms keep the mapped path but rewrite the output suffix.\n const translatedFile = getRelative(\n transformFormat\n ? replaceFileExtensionForFormat(translatedFiles[i], transformFormat)\n : translatedFiles[i]\n );\n localeMapping[sourceFile] = translatedFile;\n }\n }\n\n fileMapping[locale] = localeMapping;\n }\n\n return fileMapping;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,SAAgB,kBACd,WACA,kBACA,gBACA,kBACA,eACA,eACa;CACb,MAAM,cAA2B,EAAE;AAEnC,MAAK,MAAM,UAAU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;YAItC,QAAO,KAAK,QAAQ,cAAc;;AAKtC,YAAO;MACP;UACG;IAEL,MAAM,yBAAyB,oBAAoB,OAAO;IAC1D,MAAM,0BAA0B,oBAAoB,cAAc;AAClE,QACE,CAAC,cAAc,WACf,OAAO,cAAc,YAAY,SAEjC;IAGF,MAAM,gBAAgB,0BACpB,cAAc,SACd,uBACD;AACD,sBAAkB,gBAAgB,KAAK,aAAa;KAClD,IAAI,eAAe,YAAY,SAAS;AACxC,SACE,cAAc,SACd,OAAO,cAAc,UAAU,UAC/B;MAEA,IAAI,cAAc,cAAc;AAChC,oBAAc,0BACZ,aACA,wBACD;AAED,qBAAe,aAAa,QAC1B,IAAI,OAAO,aAAa,IAAI,EAC5B,cACD;WAED,gBAAe;AAEjB,YAAO,KAAK,QAAQ,aAAa;MACjC;;AAIN,QAAK,IAAI,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;IAC3C,MAAM,aAAa,YAAY,YAAY,GAAG;AAO9C,kBAAc,cALS,YACrB,kBACI,8BAA8B,gBAAgB,IAAI,gBAAgB,GAClE,gBAAgB,GAEoB;;;AAI9C,cAAY,UAAU;;AAGxB,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.14.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.14.56";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.14.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.14.56';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|