@intlayer/cli 8.4.3 → 8.4.5
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/dist/cjs/IntlayerEventListener.cjs +186 -1
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/cjs/_virtual/_utils_asset.cjs +98 -0
- package/dist/cjs/auth/login.cjs +90 -2
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/build.cjs +30 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/ci.cjs +76 -1
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs +485 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +15 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/editor.cjs +50 -1
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/extract.cjs +108 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/deepMergeContent.cjs +27 -1
- package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +84 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +32 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs +87 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +26 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +51 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/index.cjs +6 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +72 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +240 -1
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs +55 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs +36 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +44 -1
- package/dist/cjs/init.cjs +22 -1
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs +69 -1
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs +93 -1
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs +42 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +28 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs +153 -8
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +153 -1
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs +105 -3
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +212 -1
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +22 -1
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs +86 -3
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +73 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +98 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs +41 -1
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/index.cjs +7 -1
- package/dist/cjs/test/listMissingTranslations.cjs +52 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs +56 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/index.cjs +9 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +79 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +106 -2
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/translateDoc/validation.cjs +49 -5
- package/dist/cjs/translateDoc/validation.cjs.map +1 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs +67 -1
- package/dist/cjs/translation-alignment/alignBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs +25 -1
- package/dist/cjs/translation-alignment/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs +23 -1
- package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/index.cjs +22 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs +18 -1
- package/dist/cjs/translation-alignment/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs +22 -1
- package/dist/cjs/translation-alignment/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/translation-alignment/pipeline.cjs +37 -1
- package/dist/cjs/translation-alignment/pipeline.cjs.map +1 -1
- package/dist/cjs/translation-alignment/planActions.cjs +46 -1
- package/dist/cjs/translation-alignment/planActions.cjs.map +1 -1
- package/dist/cjs/translation-alignment/rebuildDocument.cjs +49 -2
- package/dist/cjs/translation-alignment/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/translation-alignment/segmentDocument.cjs +66 -5
- package/dist/cjs/translation-alignment/segmentDocument.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs +89 -2
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +83 -1
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs +16 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs +81 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs +19 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs +45 -1
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs +27 -3
- package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
- package/dist/cjs/utils/formatTimeDiff.cjs +20 -1
- package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +16 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs +74 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs +20 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
- package/dist/cjs/utils/listSpecialChars.cjs +54 -2
- package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs +102 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/utils/openBrowser.cjs +19 -1
- package/dist/cjs/utils/openBrowser.cjs.map +1 -1
- package/dist/cjs/utils/reorderParagraphs.cjs +91 -3
- package/dist/cjs/utils/reorderParagraphs.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs +66 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs +47 -1
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/IntlayerEventListener.mjs +183 -1
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/esm/_virtual/_utils_asset.mjs +97 -0
- package/dist/esm/auth/login.mjs +86 -2
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/build.mjs +28 -1
- package/dist/esm/build.mjs.map +1 -1
- package/dist/esm/ci.mjs +74 -1
- package/dist/esm/ci.mjs.map +1 -1
- package/dist/esm/cli.mjs +482 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +13 -1
- package/dist/esm/config.mjs.map +1 -1
- package/dist/esm/editor.mjs +50 -1
- package/dist/esm/editor.mjs.map +1 -0
- package/dist/esm/extract.mjs +104 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/deepMergeContent.mjs +25 -1
- package/dist/esm/fill/deepMergeContent.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +81 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +30 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs +85 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs +24 -1
- package/dist/esm/fill/getAvailableLocalesInDictionary.mjs.map +1 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs +49 -1
- package/dist/esm/fill/getFilterMissingContentPerLocale.mjs.map +1 -1
- package/dist/esm/fill/index.mjs +4 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +69 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +237 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs +53 -1
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs +33 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +20 -1
- package/dist/esm/init.mjs +19 -1
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initMCP.mjs +65 -1
- package/dist/esm/initMCP.mjs.map +1 -1
- package/dist/esm/initSkills.mjs +87 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs +39 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +26 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/liveSync.mjs +150 -8
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +150 -1
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs +102 -3
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +208 -1
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +20 -1
- package/dist/esm/pushConfig.mjs.map +1 -1
- package/dist/esm/pushLog.mjs +83 -3
- package/dist/esm/pushLog.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +69 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +95 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs +39 -1
- package/dist/esm/searchDoc.mjs.map +1 -1
- package/dist/esm/test/index.mjs +4 -1
- package/dist/esm/test/listMissingTranslations.mjs +49 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs +53 -1
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/index.mjs +5 -1
- package/dist/esm/translateDoc/translateDoc.mjs +75 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +103 -2
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/translateDoc/validation.mjs +46 -5
- package/dist/esm/translateDoc/validation.mjs.map +1 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs +66 -1
- package/dist/esm/translation-alignment/alignBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs +22 -1
- package/dist/esm/translation-alignment/computeSimilarity.mjs.map +1 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs +20 -1
- package/dist/esm/translation-alignment/fingerprintBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/index.mjs +11 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs +16 -1
- package/dist/esm/translation-alignment/mapChangedLinesToBlocks.mjs.map +1 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs +20 -1
- package/dist/esm/translation-alignment/normalizeBlock.mjs.map +1 -1
- package/dist/esm/translation-alignment/pipeline.mjs +35 -1
- package/dist/esm/translation-alignment/pipeline.mjs.map +1 -1
- package/dist/esm/translation-alignment/planActions.mjs +44 -1
- package/dist/esm/translation-alignment/planActions.mjs.map +1 -1
- package/dist/esm/translation-alignment/rebuildDocument.mjs +46 -2
- package/dist/esm/translation-alignment/rebuildDocument.mjs.map +1 -1
- package/dist/esm/translation-alignment/segmentDocument.mjs +64 -5
- package/dist/esm/translation-alignment/segmentDocument.mjs.map +1 -1
- package/dist/esm/utils/calculateChunks.mjs +87 -2
- package/dist/esm/utils/calculateChunks.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +79 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/checkConfigConsistency.mjs +14 -1
- package/dist/esm/utils/checkConfigConsistency.mjs.map +1 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs +80 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs +17 -1
- package/dist/esm/utils/checkLastUpdateTime.mjs.map +1 -1
- package/dist/esm/utils/chunkInference.mjs +43 -1
- package/dist/esm/utils/chunkInference.mjs.map +1 -1
- package/dist/esm/utils/fixChunkStartEndChars.mjs +25 -3
- package/dist/esm/utils/fixChunkStartEndChars.mjs.map +1 -1
- package/dist/esm/utils/formatTimeDiff.mjs +18 -1
- package/dist/esm/utils/formatTimeDiff.mjs.map +1 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs +14 -1
- package/dist/esm/utils/getIsFileUpdatedRecently.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs +72 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs +18 -1
- package/dist/esm/utils/getParentPackageJSON.mjs.map +1 -1
- package/dist/esm/utils/listSpecialChars.mjs +52 -2
- package/dist/esm/utils/listSpecialChars.mjs.map +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs +100 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
- package/dist/esm/utils/openBrowser.mjs +17 -1
- package/dist/esm/utils/openBrowser.mjs.map +1 -1
- package/dist/esm/utils/reorderParagraphs.mjs +90 -3
- package/dist/esm/utils/reorderParagraphs.mjs.map +1 -1
- package/dist/esm/utils/setupAI.mjs +63 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/esm/watch.mjs +45 -1
- package/dist/esm/watch.mjs.map +1 -1
- package/dist/types/fill/fill.d.ts +1 -1
- package/dist/types/fill/translateDictionary.d.ts +1 -1
- package/dist/types/getTargetDictionary.d.ts +19 -2
- package/dist/types/getTargetDictionary.d.ts.map +1 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
- package/dist/types/test/index.d.ts +2 -2
- package/dist/types/test/listMissingTranslations.d.ts +28 -2
- package/dist/types/test/listMissingTranslations.d.ts.map +1 -0
- package/dist/types/test/test.d.ts +11 -2
- package/dist/types/test/test.d.ts.map +1 -0
- package/dist/types/translateDoc/index.d.ts +1 -1
- package/dist/types/translateDoc/translateDoc.d.ts +1 -1
- package/dist/types/translateDoc/translateFile.d.ts +1 -1
- package/dist/types/translateDoc/types.d.ts +48 -2
- package/dist/types/translateDoc/types.d.ts.map +1 -0
- package/dist/types/utils/chunkInference.d.ts +1 -1
- package/dist/types/utils/setupAI.d.ts +21 -2
- package/dist/types/utils/setupAI.d.ts.map +1 -0
- package/package.json +12 -12
- package/dist/cjs/_utils_asset-ghp_Cjwk.cjs +0 -2
- package/dist/cjs/chunk-Bmb41Sf3.cjs +0 -1
- package/dist/esm/_utils_asset-B187VPMw.mjs +0 -2
- package/dist/esm/editor-D8BGlLzF.mjs +0 -2
- package/dist/esm/editor-D8BGlLzF.mjs.map +0 -1
- package/dist/types/getTargetDictionary-RBSRtaQj.d.ts +0 -19
- package/dist/types/getTargetDictionary-RBSRtaQj.d.ts.map +0 -1
- package/dist/types/listMissingTranslations-DxKw7nqI.d.ts +0 -28
- package/dist/types/listMissingTranslations-DxKw7nqI.d.ts.map +0 -1
- package/dist/types/setupAI-Bosjx7ah.d.ts +0 -21
- package/dist/types/setupAI-Bosjx7ah.d.ts.map +0 -1
- package/dist/types/test-DUTiJR5_.d.ts +0 -11
- package/dist/types/test-DUTiJR5_.d.ts.map +0 -1
- package/dist/types/types-BKvc3FmV.d.ts +0 -48
- package/dist/types/types-BKvc3FmV.d.ts.map +0 -1
|
@@ -1,2 +1,50 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { logConfigDetails } from "@intlayer/chokidar/cli";
|
|
2
|
+
import { getConfiguration } from "@intlayer/config/node";
|
|
3
|
+
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
4
|
+
import { getMissingLocalesContentFromDictionary } from "@intlayer/core/plugins";
|
|
5
|
+
import { getDictionaries } from "@intlayer/dictionaries-entry";
|
|
6
|
+
|
|
7
|
+
//#region src/test/listMissingTranslations.ts
|
|
8
|
+
const listMissingTranslationsWithConfig = (configuration) => {
|
|
9
|
+
const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);
|
|
10
|
+
const mergedDictionaries = getDictionaries(configuration);
|
|
11
|
+
const missingTranslations = [];
|
|
12
|
+
const { locales, requiredLocales } = configuration.internationalization;
|
|
13
|
+
const dictionariesKeys = Object.keys(unmergedDictionariesRecord);
|
|
14
|
+
for (const dictionaryKey of dictionariesKeys) {
|
|
15
|
+
const dictionaries = unmergedDictionariesRecord[dictionaryKey];
|
|
16
|
+
const multilingualDictionary = dictionaries.filter((dictionary) => !dictionary.locale);
|
|
17
|
+
for (const dictionary of multilingualDictionary) {
|
|
18
|
+
const missingLocales = getMissingLocalesContentFromDictionary(dictionary, locales);
|
|
19
|
+
if (missingLocales.length > 0) missingTranslations.push({
|
|
20
|
+
key: dictionaryKey,
|
|
21
|
+
id: dictionary.id,
|
|
22
|
+
filePath: dictionary.filePath,
|
|
23
|
+
locales: missingLocales
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
if (dictionaries.filter((dictionary) => dictionary.locale).length === 0) continue;
|
|
27
|
+
const mergedDictionary = mergedDictionaries[dictionaryKey];
|
|
28
|
+
const missingLocales = getMissingLocalesContentFromDictionary(mergedDictionary, locales);
|
|
29
|
+
if (missingLocales.length > 0) missingTranslations.push({
|
|
30
|
+
key: dictionaryKey,
|
|
31
|
+
locales: missingLocales
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const missingLocalesSet = new Set(missingTranslations.flatMap((t) => t.locales));
|
|
35
|
+
const missingLocales = Array.from(missingLocalesSet);
|
|
36
|
+
return {
|
|
37
|
+
missingTranslations,
|
|
38
|
+
missingLocales,
|
|
39
|
+
missingRequiredLocales: missingLocales.filter((locale) => (requiredLocales ?? locales).includes(locale))
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
const listMissingTranslations = (configurationOptions) => {
|
|
43
|
+
const configuration = getConfiguration(configurationOptions);
|
|
44
|
+
logConfigDetails(configurationOptions);
|
|
45
|
+
return listMissingTranslationsWithConfig(configuration);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
export { listMissingTranslations, listMissingTranslationsWithConfig };
|
|
2
50
|
//# sourceMappingURL=listMissingTranslations.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n const dictionariesKeys = Object.keys(unmergedDictionariesRecord);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap((t) => t.locales)\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n const dictionariesKeys = Object.keys(unmergedDictionariesRecord);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap((t) => t.locales)\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":";;;;;;;AAYA,MAAa,qCACX,kBACG;CACH,MAAM,6BAA6B,wBAAwB,cAAc;CACzE,MAAM,qBAAqB,gBAAgB,cAAc;CAEzD,MAAM,sBAKA,EAAE;CAER,MAAM,EAAE,SAAS,oBAAoB,cAAc;CAEnD,MAAM,mBAAmB,OAAO,KAAK,2BAA2B;AAEhE,MAAK,MAAM,iBAAiB,kBAAkB;EAC5C,MAAM,eACJ,2BAA2B;EAE7B,MAAM,yBAAuC,aAAa,QACvD,eAAe,CAAC,WAAW,OAC7B;AAGD,OAAK,MAAM,cAAc,wBAAwB;GAC/C,MAAM,iBAAiB,uCACrB,YACA,QACD;AAED,OAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;IACvB,KAAK;IACL,IAAI,WAAW;IACf,UAAU,WAAW;IACrB,SAAS;IACV,CAAC;;AAQN,MAJ0C,aAAa,QACpD,eAAe,WAAW,OAC5B,CAEuB,WAAW,EACjC;EAGF,MAAM,mBAAmB,mBAAmB;EAE5C,MAAM,iBAAiB,uCACrB,kBACA,QACD;AAED,MAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;GACvB,KAAK;GACL,SAAS;GACV,CAAC;;CAIN,MAAM,oBAAoB,IAAI,IAC5B,oBAAoB,SAAS,MAAM,EAAE,QAAQ,CAC9C;CACD,MAAM,iBAAiB,MAAM,KAAK,kBAAkB;AAMpD,QAAO;EAAE;EAAqB;EAAgB,wBAJf,eAAe,QAAQ,YACnD,mBAAmB,SAAS,SAAS,OAAO,CAC9C;EAEqE;;AAGxE,MAAa,2BACX,yBACG;CACH,MAAM,gBAAgB,iBAAiB,qBAAqB;AAC5D,kBAAiB,qBAAqB;AAEtC,QAAO,kCAAkC,cAAc"}
|
package/dist/esm/test/test.mjs
CHANGED
|
@@ -1,2 +1,54 @@
|
|
|
1
|
-
import{listMissingTranslations
|
|
1
|
+
import { listMissingTranslations } from "./listMissingTranslations.mjs";
|
|
2
|
+
import { prepareIntlayer } from "@intlayer/chokidar/build";
|
|
3
|
+
import { formatLocale, formatPath } from "@intlayer/chokidar/utils";
|
|
4
|
+
import * as ANSIColors from "@intlayer/config/colors";
|
|
5
|
+
import { colon, colorize, colorizeKey, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
|
|
6
|
+
import { getConfiguration } from "@intlayer/config/node";
|
|
7
|
+
|
|
8
|
+
//#region src/test/test.ts
|
|
9
|
+
const testMissingTranslations = async (options) => {
|
|
10
|
+
const config = getConfiguration(options?.configOptions);
|
|
11
|
+
const { locales, requiredLocales } = config.internationalization;
|
|
12
|
+
const appLogger = getAppLogger(config);
|
|
13
|
+
if (options?.build === true) await prepareIntlayer(config, { forceRun: true });
|
|
14
|
+
else if (typeof options?.build === "undefined") await prepareIntlayer(config);
|
|
15
|
+
const result = listMissingTranslations(options?.configOptions);
|
|
16
|
+
const maxKeyColSize = result.missingTranslations.map((t) => ` - ${t.key}`).reduce((max, t) => Math.max(max, t.length), 0);
|
|
17
|
+
const maxLocalesColSize = result.missingTranslations.map((t) => formatLocale(t.locales, false)).reduce((max, t) => Math.max(max, t.length), 0);
|
|
18
|
+
const formattedMissingTranslations = result.missingTranslations.map((translation) => [
|
|
19
|
+
colon(` - ${colorizeKey(translation.key)}`, {
|
|
20
|
+
colSize: maxKeyColSize,
|
|
21
|
+
maxSize: 40
|
|
22
|
+
}),
|
|
23
|
+
" - ",
|
|
24
|
+
colon(formatLocale(translation.locales, ANSIColors.RED), {
|
|
25
|
+
colSize: maxLocalesColSize,
|
|
26
|
+
maxSize: 40
|
|
27
|
+
}),
|
|
28
|
+
translation.filePath ? ` - ${formatPath(translation.filePath)}` : "",
|
|
29
|
+
translation.id ? " - remote" : ""
|
|
30
|
+
].join(""));
|
|
31
|
+
appLogger(`Missing translations:`, { level: "info" });
|
|
32
|
+
formattedMissingTranslations.forEach((t) => {
|
|
33
|
+
appLogger(t, { level: "info" });
|
|
34
|
+
});
|
|
35
|
+
appLogger(`Locales: ${formatLocale(locales)}`);
|
|
36
|
+
appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);
|
|
37
|
+
appLogger(`Missing locales: ${result.missingLocales.length === 0 ? colorize("-", ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`);
|
|
38
|
+
appLogger(`Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize("-", ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`);
|
|
39
|
+
appLogger(`Total missing locales: ${colorizeNumber(result.missingLocales.length, {
|
|
40
|
+
one: ANSIColors.RED,
|
|
41
|
+
other: ANSIColors.RED,
|
|
42
|
+
zero: ANSIColors.GREEN
|
|
43
|
+
})}`);
|
|
44
|
+
appLogger(`Total missing required locales: ${colorizeNumber(result.missingRequiredLocales.length, {
|
|
45
|
+
one: ANSIColors.RED,
|
|
46
|
+
other: ANSIColors.RED,
|
|
47
|
+
zero: ANSIColors.GREEN
|
|
48
|
+
})}`);
|
|
49
|
+
if (result.missingRequiredLocales.length > 0) process.exit(1);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
export { testMissingTranslations };
|
|
2
54
|
//# sourceMappingURL=test.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test.mjs","names":[],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { listMissingTranslations } from './listMissingTranslations';\n\ntype ListMissingTranslationsOptions = {\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\nexport const testMissingTranslations = async (\n options?: ListMissingTranslationsOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n const { locales, requiredLocales } = config.internationalization;\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n const result = listMissingTranslations(options?.configOptions);\n\n const maxKeyColSize = result.missingTranslations\n .map((t) => ` - ${t.key}`)\n .reduce((max, t) => Math.max(max, t.length), 0);\n const maxLocalesColSize = result.missingTranslations\n .map((t) => formatLocale(t.locales, false))\n .reduce((max, t) => Math.max(max, t.length), 0);\n\n const formattedMissingTranslations = result.missingTranslations.map(\n (translation) =>\n [\n colon(` - ${colorizeKey(translation.key)}`, {\n colSize: maxKeyColSize,\n maxSize: 40,\n }),\n ' - ',\n colon(formatLocale(translation.locales, ANSIColors.RED), {\n colSize: maxLocalesColSize,\n maxSize: 40,\n }),\n\n translation.filePath ? ` - ${formatPath(translation.filePath)}` : '',\n translation.id ? ' - remote' : '',\n ].join('')\n );\n\n appLogger(`Missing translations:`, {\n level: 'info',\n });\n\n formattedMissingTranslations.forEach((t) => {\n appLogger(t, {\n level: 'info',\n });\n });\n\n appLogger(`Locales: ${formatLocale(locales)}`);\n appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);\n appLogger(\n `Missing locales: ${result.missingLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`\n );\n\n appLogger(\n `Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`\n );\n appLogger(\n `Total missing locales: ${colorizeNumber(result.missingLocales.length, {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n })}`\n );\n appLogger(\n `Total missing required locales: ${colorizeNumber(\n result.missingRequiredLocales.length,\n {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n }\n )}`\n );\n\n if (result.missingRequiredLocales.length > 0) {\n process.exit(1);\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"test.mjs","names":[],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { listMissingTranslations } from './listMissingTranslations';\n\ntype ListMissingTranslationsOptions = {\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\nexport const testMissingTranslations = async (\n options?: ListMissingTranslationsOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n const { locales, requiredLocales } = config.internationalization;\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n const result = listMissingTranslations(options?.configOptions);\n\n const maxKeyColSize = result.missingTranslations\n .map((t) => ` - ${t.key}`)\n .reduce((max, t) => Math.max(max, t.length), 0);\n const maxLocalesColSize = result.missingTranslations\n .map((t) => formatLocale(t.locales, false))\n .reduce((max, t) => Math.max(max, t.length), 0);\n\n const formattedMissingTranslations = result.missingTranslations.map(\n (translation) =>\n [\n colon(` - ${colorizeKey(translation.key)}`, {\n colSize: maxKeyColSize,\n maxSize: 40,\n }),\n ' - ',\n colon(formatLocale(translation.locales, ANSIColors.RED), {\n colSize: maxLocalesColSize,\n maxSize: 40,\n }),\n\n translation.filePath ? ` - ${formatPath(translation.filePath)}` : '',\n translation.id ? ' - remote' : '',\n ].join('')\n );\n\n appLogger(`Missing translations:`, {\n level: 'info',\n });\n\n formattedMissingTranslations.forEach((t) => {\n appLogger(t, {\n level: 'info',\n });\n });\n\n appLogger(`Locales: ${formatLocale(locales)}`);\n appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);\n appLogger(\n `Missing locales: ${result.missingLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`\n );\n\n appLogger(\n `Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`\n );\n appLogger(\n `Total missing locales: ${colorizeNumber(result.missingLocales.length, {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n })}`\n );\n appLogger(\n `Total missing required locales: ${colorizeNumber(\n result.missingRequiredLocales.length,\n {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANS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I,SAAS,KAAK,WAAW,MAAM,GAAG,aAAa,OAAO,gBAAgB,WAAW,IAAI,GAC/I;AAED,WACE,6BAA6B,OAAO,uBAAuB,WAAW,IAAI,SAAS,KAAK,WAAW,MAAM,GAAG,aAAa,OAAO,wBAAwB,WAAW,IAAI,GACxK;AACD,WACE,0BAA0B,eAAe,OAAO,eAAe,QAAQ;EACrE,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,MAAM,WAAW;EAClB,CAAC,GACH;AACD,WACE,mCAAmC,eACjC,OAAO,uBAAuB,QAC9B;EACE,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,MAAM,WAAW;EAClB,CACF,GACF;AAED,KAAI,OAAO,uBAAuB,SAAS,EACzC,SAAQ,KAAK,EAAE"}
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { sanitizeChunk, validateTranslation } from "./validation.mjs";
|
|
2
|
+
import { translateFile } from "./translateFile.mjs";
|
|
3
|
+
import { translateDoc } from "./translateDoc.mjs";
|
|
4
|
+
|
|
5
|
+
export { sanitizeChunk, translateDoc, translateFile, validateTranslation };
|
|
@@ -1,2 +1,76 @@
|
|
|
1
|
-
import{setupAI
|
|
1
|
+
import { setupAI } from "../utils/setupAI.mjs";
|
|
2
|
+
import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
|
|
3
|
+
import { getOutputFilePath } from "../utils/getOutputFilePath.mjs";
|
|
4
|
+
import { translateFile } from "./translateFile.mjs";
|
|
5
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { listGitFiles, logConfigDetails } from "@intlayer/chokidar/cli";
|
|
8
|
+
import { pLimit, parallelize } from "@intlayer/chokidar/utils";
|
|
9
|
+
import * as ANSIColors from "@intlayer/config/colors";
|
|
10
|
+
import { colorize, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
|
|
11
|
+
import { getConfiguration } from "@intlayer/config/node";
|
|
12
|
+
import fg from "fast-glob";
|
|
13
|
+
import { performance } from "node:perf_hooks";
|
|
14
|
+
|
|
15
|
+
//#region src/translateDoc/translateDoc.ts
|
|
16
|
+
const translateDoc = async ({ docPattern, locales, excludedGlobPattern, baseLocale, aiOptions, nbSimultaneousFileProcessed = 20, configOptions, customInstructions, skipIfModifiedBefore, skipIfModifiedAfter, skipIfExists, gitOptions, flushStrategy = "incremental" }) => {
|
|
17
|
+
const configuration = getConfiguration(configOptions);
|
|
18
|
+
logConfigDetails(configOptions);
|
|
19
|
+
const appLogger = getAppLogger(configuration);
|
|
20
|
+
const maxConcurrentChunks = nbSimultaneousFileProcessed;
|
|
21
|
+
const globalChunkLimiter = pLimit(maxConcurrentChunks);
|
|
22
|
+
let docList = await fg(docPattern, { ignore: excludedGlobPattern });
|
|
23
|
+
const aiResult = await setupAI(configuration, aiOptions);
|
|
24
|
+
if (!aiResult?.hasAIAccess) return;
|
|
25
|
+
const { aiClient, aiConfig } = aiResult;
|
|
26
|
+
if (gitOptions) {
|
|
27
|
+
const gitChangedFiles = await listGitFiles(gitOptions);
|
|
28
|
+
if (gitChangedFiles) docList = docList.filter((path) => gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile));
|
|
29
|
+
}
|
|
30
|
+
const batchStartTime = performance.now();
|
|
31
|
+
appLogger(`Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \nGlobal Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`);
|
|
32
|
+
const errorState = {
|
|
33
|
+
count: 0,
|
|
34
|
+
maxErrors: 5,
|
|
35
|
+
shouldStop: false
|
|
36
|
+
};
|
|
37
|
+
await parallelize(docList.flatMap((docPath) => locales.map((locale) => async () => {
|
|
38
|
+
if (errorState.shouldStop) return;
|
|
39
|
+
const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);
|
|
40
|
+
const outputFilePath = getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
|
|
41
|
+
if (skipIfExists && existsSync(outputFilePath)) return;
|
|
42
|
+
if (flushStrategy === "incremental" && !existsSync(outputFilePath)) {
|
|
43
|
+
mkdirSync(dirname(outputFilePath), { recursive: true });
|
|
44
|
+
writeFileSync(outputFilePath, "");
|
|
45
|
+
}
|
|
46
|
+
const fileModificationData = checkFileModifiedRange(outputFilePath, {
|
|
47
|
+
skipIfModifiedBefore,
|
|
48
|
+
skipIfModifiedAfter
|
|
49
|
+
});
|
|
50
|
+
if (fileModificationData.isSkipped) {
|
|
51
|
+
appLogger(fileModificationData.message);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
await translateFile({
|
|
55
|
+
baseFilePath: absoluteBaseFilePath,
|
|
56
|
+
outputFilePath,
|
|
57
|
+
locale,
|
|
58
|
+
baseLocale,
|
|
59
|
+
configuration,
|
|
60
|
+
errorState,
|
|
61
|
+
aiOptions,
|
|
62
|
+
customInstructions,
|
|
63
|
+
aiClient,
|
|
64
|
+
aiConfig,
|
|
65
|
+
flushStrategy,
|
|
66
|
+
limit: globalChunkLimiter
|
|
67
|
+
});
|
|
68
|
+
})), (task) => task(), 50);
|
|
69
|
+
const batchDuration = ((performance.now() - batchStartTime) / 1e3).toFixed(2);
|
|
70
|
+
if (errorState.count > 0) appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);
|
|
71
|
+
else appLogger(`${colorize("✔", ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
//#endregion
|
|
75
|
+
export { translateDoc };
|
|
2
76
|
//# sourceMappingURL=translateDoc.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateDoc.mjs","names":[],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { translateFile } from './translateFile';\nimport type { ErrorState, TranslateDocOptions } from './types';\n\nexport const translateDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed = 20, // Default to a higher concurrency for chunks\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n flushStrategy = 'incremental',\n}: TranslateDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n // 1. GLOBAL QUEUE SETUP\n // We use pLimit to create a single bottleneck for AI requests.\n // This queue is shared across all files and locales.\n const maxConcurrentChunks = nbSimultaneousFileProcessed;\n const globalChunkLimiter = pLimit(maxConcurrentChunks);\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n const aiResult = await setupAI(configuration, aiOptions);\n if (!aiResult?.hasAIAccess) return;\n const { aiClient, aiConfig } = aiResult;\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n if (gitChangedFiles) {\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n const batchStartTime = performance.now();\n\n appLogger(\n `Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \\n` +\n `Global Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`\n );\n\n const errorState: ErrorState = {\n count: 0,\n maxErrors: 5,\n shouldStop: false,\n };\n\n // 2. FLATTENED TASK LIST\n // We create a task for every File x Locale combination.\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n if (errorState.shouldStop) return;\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip logic\n if (skipIfExists && existsSync(outputFilePath)) return;\n\n if (flushStrategy === 'incremental' && !existsSync(outputFilePath)) {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, '');\n }\n\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n\n // Execute translation using the SHARED limiter\n await translateFile({\n baseFilePath: absoluteBaseFilePath,\n outputFilePath,\n locale: locale as Locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy,\n limit: globalChunkLimiter, // Pass the global queue\n });\n })\n );\n\n // 3. HIGH-THROUGHPUT FILE OPENER\n // We open many files simultaneously (e.g., 50) to ensure the global chunk queue\n // is always saturated with work.\n // If we open too few files, the chunk queue might drain faster than we can read new files.\n const FILE_OPEN_LIMIT = 50;\n\n await parallelize(allTasks, (task) => task(), FILE_OPEN_LIMIT);\n\n const batchEndTime = performance.now();\n const batchDuration = ((batchEndTime - batchStartTime) / 1000).toFixed(2);\n\n if (errorState.count > 0) {\n appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);\n } else {\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`\n );\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"translateDoc.mjs","names":[],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { translateFile } from './translateFile';\nimport type { ErrorState, TranslateDocOptions } from './types';\n\nexport const translateDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed = 20, // Default to a higher concurrency for chunks\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n flushStrategy = 'incremental',\n}: TranslateDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n // 1. GLOBAL QUEUE SETUP\n // We use pLimit to create a single bottleneck for AI requests.\n // This queue is shared across all files and locales.\n const maxConcurrentChunks = nbSimultaneousFileProcessed;\n const globalChunkLimiter = pLimit(maxConcurrentChunks);\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n const aiResult = await setupAI(configuration, aiOptions);\n if (!aiResult?.hasAIAccess) return;\n const { aiClient, aiConfig } = aiResult;\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n if (gitChangedFiles) {\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n const batchStartTime = performance.now();\n\n appLogger(\n `Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \\n` +\n `Global Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`\n );\n\n const errorState: ErrorState = {\n count: 0,\n maxErrors: 5,\n shouldStop: false,\n };\n\n // 2. FLATTENED TASK LIST\n // We create a task for every File x Locale combination.\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n if (errorState.shouldStop) return;\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip logic\n if (skipIfExists && existsSync(outputFilePath)) return;\n\n if (flushStrategy === 'incremental' && !existsSync(outputFilePath)) {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, '');\n }\n\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n\n // Execute translation using the SHARED limiter\n await translateFile({\n baseFilePath: absoluteBaseFilePath,\n outputFilePath,\n locale: locale as Locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy,\n limit: globalChunkLimiter, // Pass the global queue\n });\n })\n );\n\n // 3. HIGH-THROUGHPUT FILE OPENER\n // We open many files simultaneously (e.g., 50) to ensure the global chunk queue\n // is always saturated with work.\n // If we open too few files, the chunk queue might drain faster than we can read new files.\n const FILE_OPEN_LIMIT = 50;\n\n await parallelize(allTasks, (task) => task(), FILE_OPEN_LIMIT);\n\n const batchEndTime = performance.now();\n const batchDuration = ((batchEndTime - batchStartTime) / 1000).toFixed(2);\n\n if (errorState.count > 0) {\n appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);\n } else {\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,eAAe,OAAO,EACjC,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U,qBAAqB,QAAQ;AACvC;;AAIF,QAAM,cAAc;GAClB,cAAc;GACd;GACQ;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACR,CAAC;GACF,CACH,GAQ4B,SAAS,MAAM,EAFpB,GAEsC;CAG9D,MAAM,kBADe,YAAY,KAAK,GACC,kBAAkB,KAAM,QAAQ,EAAE;AAEzE,KAAI,WAAW,QAAQ,EACrB,WAAU,iBAAiB,WAAW,MAAM,aAAa,cAAc,IAAI;KAE3E,WACE,GAAG,SAAS,KAAK,WAAW,MAAM,CAAC,mCAAmC,eAAe,cAAc,CAAC,IACrG"}
|
|
@@ -1,3 +1,104 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import { readAsset } from "../_virtual/_utils_asset.mjs";
|
|
2
|
+
import { sanitizeChunk, validateTranslation } from "./validation.mjs";
|
|
3
|
+
import { chunkInference } from "../utils/chunkInference.mjs";
|
|
4
|
+
import { fixChunkStartEndChars } from "../utils/fixChunkStartEndChars.mjs";
|
|
5
|
+
import { chunkText } from "../utils/calculateChunks.mjs";
|
|
6
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, relative } from "node:path";
|
|
8
|
+
import { formatLocale, formatPath } from "@intlayer/chokidar/utils";
|
|
9
|
+
import * as ANSIColors from "@intlayer/config/colors";
|
|
10
|
+
import { colon, colorize, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
|
|
11
|
+
import { retryManager } from "@intlayer/config/utils";
|
|
12
|
+
import { readFile } from "node:fs/promises";
|
|
13
|
+
import { performance } from "node:perf_hooks";
|
|
14
|
+
|
|
15
|
+
//#region src/translateDoc/translateFile.ts
|
|
16
|
+
const translateFile = async ({ baseFilePath, outputFilePath, locale, baseLocale, configuration, errorState, aiOptions, customInstructions, aiClient, aiConfig, flushStrategy = "incremental", onChunkReceive, limit }) => {
|
|
17
|
+
if (errorState.shouldStop) return null;
|
|
18
|
+
const appLogger = getAppLogger(configuration, { config: { prefix: "" } });
|
|
19
|
+
const fileStartTime = performance.now();
|
|
20
|
+
try {
|
|
21
|
+
const chunks = chunkText(await readFile(baseFilePath, "utf-8"));
|
|
22
|
+
const totalChunks = chunks.length;
|
|
23
|
+
const filePrefix = `${colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `, { colSize: 40 })}${ANSIColors.RESET}`;
|
|
24
|
+
const prefix = `${colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `, { colSize: 40 })}${ANSIColors.RESET}`;
|
|
25
|
+
appLogger(`${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`);
|
|
26
|
+
const basePrompt = readAsset("./prompts/TRANSLATE_PROMPT.md", "utf-8").replaceAll("{{localeName}}", `${formatLocale(locale, false)}`).replaceAll("{{baseLocaleName}}", `${formatLocale(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
|
|
27
|
+
const translatedParts = new Array(totalChunks).fill("");
|
|
28
|
+
const runTask = limit ?? ((fn) => fn());
|
|
29
|
+
const tasks = chunks.map((chunk, i) => runTask(async () => {
|
|
30
|
+
if (errorState.shouldStop) return null;
|
|
31
|
+
const chunkLogger = getAppLogger(configuration, { config: { prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}` } });
|
|
32
|
+
const chunkStartTime = performance.now();
|
|
33
|
+
const isFirstChunk = i === 0;
|
|
34
|
+
const fileToTranslateCurrentChunk = chunk.content;
|
|
35
|
+
const getPrevChunkPrompt = () => `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n\`\`\`\n` + (chunks[i - 1]?.content ?? "") + `\n\`\`\`\n>>> END PREVIOUS CONTEXT <<<`;
|
|
36
|
+
const getBaseChunkContextPrompt = () => `>>> CONTEXT: NEXT CONTENT <<<\n\`\`\`\n` + (chunks[i + 1]?.content ?? "") + `\n\`\`\`\n>>> END NEXT CONTEXT <<<`;
|
|
37
|
+
chunkLogger("Process started");
|
|
38
|
+
const { content: translatedChunk, tokens } = await retryManager(async () => {
|
|
39
|
+
const result = await chunkInference([
|
|
40
|
+
{
|
|
41
|
+
role: "system",
|
|
42
|
+
content: basePrompt
|
|
43
|
+
},
|
|
44
|
+
...chunks[i + 1] ? [{
|
|
45
|
+
role: "system",
|
|
46
|
+
content: getBaseChunkContextPrompt()
|
|
47
|
+
}] : [],
|
|
48
|
+
...isFirstChunk ? [] : [{
|
|
49
|
+
role: "system",
|
|
50
|
+
content: getPrevChunkPrompt()
|
|
51
|
+
}],
|
|
52
|
+
{
|
|
53
|
+
role: "system",
|
|
54
|
+
content: [`You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`, `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`].join("\n")
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
role: "user",
|
|
58
|
+
content: `>>> TARGET CHUNK START <<<\n${fileToTranslateCurrentChunk}\n>>> TARGET CHUNK END <<<`
|
|
59
|
+
}
|
|
60
|
+
], aiOptions, configuration, aiClient, aiConfig);
|
|
61
|
+
let processedChunk = sanitizeChunk(result?.fileContent, fileToTranslateCurrentChunk);
|
|
62
|
+
processedChunk = fixChunkStartEndChars(processedChunk, fileToTranslateCurrentChunk);
|
|
63
|
+
if (!validateTranslation(fileToTranslateCurrentChunk, processedChunk, chunkLogger)) throw new Error(`Validation failed for chunk ${i + 1}/${totalChunks}`);
|
|
64
|
+
return {
|
|
65
|
+
content: processedChunk,
|
|
66
|
+
tokens: result.tokenUsed
|
|
67
|
+
};
|
|
68
|
+
})();
|
|
69
|
+
const chunkDuration = (performance.now() - chunkStartTime).toFixed(0);
|
|
70
|
+
translatedParts[i] = translatedChunk;
|
|
71
|
+
if (onChunkReceive) onChunkReceive(translatedChunk, i, totalChunks);
|
|
72
|
+
if (flushStrategy === "incremental") {
|
|
73
|
+
if (translatedParts.slice(0, i + 1).every((p) => p && p !== "")) {
|
|
74
|
+
let endIdx = 0;
|
|
75
|
+
while (endIdx < totalChunks && translatedParts[endIdx] && translatedParts[endIdx] !== "") endIdx++;
|
|
76
|
+
const currentContent = translatedParts.slice(0, endIdx).join("");
|
|
77
|
+
mkdirSync(dirname(outputFilePath), { recursive: true });
|
|
78
|
+
writeFileSync(outputFilePath, currentContent);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
chunkLogger([`${colorizeNumber(tokens)} tokens used `, `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`].join(""));
|
|
82
|
+
}));
|
|
83
|
+
await Promise.all(tasks);
|
|
84
|
+
const fullContent = translatedParts.join("");
|
|
85
|
+
if (flushStrategy === "end" || flushStrategy === "incremental") {
|
|
86
|
+
mkdirSync(dirname(outputFilePath), { recursive: true });
|
|
87
|
+
writeFileSync(outputFilePath, fullContent);
|
|
88
|
+
}
|
|
89
|
+
const totalDuration = ((performance.now() - fileStartTime) / 1e3).toFixed(2);
|
|
90
|
+
const relativePath = relative(configuration.system.baseDir, outputFilePath);
|
|
91
|
+
appLogger(`${colorize("✔", ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`);
|
|
92
|
+
return fullContent;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
errorState.count++;
|
|
95
|
+
const errorMessage = error?.message ?? JSON.stringify(error);
|
|
96
|
+
appLogger(`${colorize("✖", ANSIColors.RED)} Error: ${errorMessage}`);
|
|
97
|
+
if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
//#endregion
|
|
103
|
+
export { translateFile };
|
|
3
104
|
//# sourceMappingURL=translateFile.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"2wBAoBA,MAAa,EAAgB,MAAO,CAClC,eACA,iBACA,SACA,aACA,gBACA,aACA,YACA,qBACA,WACA,WACA,gBAAgB,cAChB,iBACA,WACkD,CAClD,GAAI,EAAW,WAAY,OAAO,KAElC,IAAM,EAAY,EAAa,EAAe,CAAE,OAAQ,CAAE,OAAQ,GAAI,CAAE,CAAC,CACnE,EAAgB,EAAY,KAAK,CAEvC,GAAI,CAEF,IAAM,EAAS,EADK,MAAM,EAAS,EAAc,QAAQ,CACpB,CAC/B,EAAc,EAAO,OAGrB,EAAa,GAAG,EADC,GAAG,EAAW,UAAU,GAAG,EAAW,EAAa,GAAG,EAAW,UAAU,IACtD,CAAE,QAAS,GAAI,CAAC,GAAG,EAAW,QAEpE,EAAS,GAAG,EADC,GAAG,EAAW,UAAU,GAAG,EAAW,EAAa,GAAG,EAAW,UAAU,IAAI,EAAa,EAAO,GAAG,EAAW,UAAU,IAC1G,CAAE,QAAS,GAAI,CAAC,GAAG,EAAW,QAElE,EACE,GAAG,EAAW,aAAa,EAAe,EAAY,CAAC,qBACxD,CAED,IAAM,EAAa,EAAU,gCAAiC,QAAQ,CACnE,WAAW,iBAAkB,GAAG,EAAa,EAAQ,GAAM,GAAG,CAC9D,WAAW,qBAAsB,GAAG,EAAa,EAAY,GAAM,GAAG,CACtE,QAAQ,yBAA0B,GAAW,oBAAsB,IAAI,CACvE,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,QAAQ,EAAE,CAUhE,GAPA,EAAgB,GAAK,EAEjB,GACF,EAAe,EAAiB,EAAG,EAAY,CAI7C,IAAkB,eACC,EAClB,MAAM,EAAG,EAAI,EAAE,CACf,MAAO,GAAM,GAAK,IAAM,GAAG,CAEZ,CAChB,IAAI,EAAS,EACb,KACE,EAAS,GACT,EAAgB,IAChB,EAAgB,KAAY,IAE5B,IAEF,IAAM,EAAiB,EAAgB,MAAM,EAAG,EAAO,CAAC,KAAK,GAAG,CAEhE,EAAU,EAAQ,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,CACvD,EAAc,EAAgB,EAAe,CAIjD,EACE,CACE,GAAG,EAAe,EAAO,CAAC,eAC1B,GAAG,EAAW,UAAU,KAAK,EAAe,EAAc,CAAC,IAAI,EAAW,QAC3E,CAAC,KAAK,GAAG,CACX,EACD,CACH,CAGD,MAAM,QAAQ,IAAI,EAAM,CAGxB,IAAM,EAAc,EAAgB,KAAK,GAAG,EACxC,IAAkB,OAAS,IAAkB,iBAC/C,EAAU,EAAQ,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,CACvD,EAAc,EAAgB,EAAY,EAI5C,IAAM,IADc,EAAY,KAAK,CACC,GAAiB,KAAM,QAAQ,EAAE,CACjE,EAAe,EAAS,EAAc,OAAO,QAAS,EAAe,CAM3E,OAJA,EACE,GAAG,EAAS,IAAK,EAAW,MAAM,CAAC,QAAQ,EAAW,EAAa,CAAC,gBAAgB,EAAe,EAAc,CAAC,IACnH,CAEM,QACA,EAAY,CACnB,EAAW,QACX,IAAM,EAAe,GAAO,SAAW,KAAK,UAAU,EAAM,CAG5D,OAFA,EAAU,GAAG,EAAS,IAAK,EAAW,IAAI,CAAC,UAAU,IAAe,CAChE,EAAW,OAAS,EAAW,YAAW,EAAW,WAAa,IAC/D"}
|
|
1
|
+
{"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,gBAAgB,OAAO,EAClC,cACA,gBACA,QACA,YACA,eACA,YACA,WACA,oBACA,UACA,UACA,gBAAgB,eAChB,gBACA,YACkD;AAClD,KAAI,WAAW,WAAY,QAAO;CAElC,MAAM,YAAY,aAAa,eAAe,EAAE,QAAQ,EAAE,QAAQ,IAAI,EAAE,CAAC;CACzE,MAAM,gBAAgB,YAAY,KAAK;AAEvC,KAAI;EAEF,MAAM,SAAS,UADK,MAAM,SAAS,cAAc,QAAQ,CACpB;EACrC,MAAM,cAAc,OAAO;EAG3B,MAAM,aAAa,GAAG,MADC,GAAG,WAAW,UAAU,GAAG,WAAW,aAAa,GAAG,WAAW,UAAU,KACtD,EAAE,SAAS,IAAI,CAAC,GAAG,WAAW;EAE1E,MAAM,SAAS,GAAG,MADC,GAAG,WAAW,UAAU,GAAG,WAAW,aAAa,GAAG,WAAW,UAAU,IAAI,aAAa,OAAO,GAAG,WAAW,UAAU,KAC1G,EAAE,SAAS,IAAI,CAAC,GAAG,WAAW;AAElE,YACE,GAAG,WAAW,aAAa,eAAe,YAAY,CAAC,qBACxD;EAED,MAAM,aAAa,UAAU,iCAAiC,QAAQ,CACnE,WAAW,kBAAkB,GAAG,aAAa,QAAQ,MAAM,GAAG,CAC9D,WAAW,sBAAsB,GAAG,aAAa,YAAY,MAAM,GAAG,CACtE,QAAQ,0BAA0B,WAAW,sBAAsB,IAAI,CACvE,QAAQ,0BAA0B,sBAAsB,IAAI;EAE/D,MAAM,kBAA4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1,6 +1,47 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
//#region src/translateDoc/validation.ts
|
|
2
|
+
/**
|
|
3
|
+
* Validates that the translated content matches the structure of the original.
|
|
4
|
+
* Throws an error if a mismatch is found, triggering a retry.
|
|
5
|
+
*/
|
|
6
|
+
const validateTranslation = (original, translated, logger) => {
|
|
7
|
+
const errors = [];
|
|
8
|
+
if (original.trimStart().startsWith("---")) {
|
|
9
|
+
if (!translated.trimStart().startsWith("---")) errors.push("YAML Frontmatter missing: Input starts with \"---\", output does not.");
|
|
10
|
+
const originalDashes = (original.match(/^---$/gm) || []).length;
|
|
11
|
+
const translatedDashes = (translated.match(/^---$/gm) || []).length;
|
|
12
|
+
if (originalDashes >= 2 && translatedDashes < 2) errors.push("YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.");
|
|
13
|
+
}
|
|
14
|
+
const fenceRegex = /^\s*```/gm;
|
|
15
|
+
const originalFences = (original.match(fenceRegex) || []).length;
|
|
16
|
+
const translatedFences = (translated.match(fenceRegex) || []).length;
|
|
17
|
+
if (originalFences !== translatedFences) errors.push(`Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`);
|
|
18
|
+
const ratio = translated.length / (original.length || 1);
|
|
19
|
+
const isTooLong = ratio > 2.5;
|
|
20
|
+
const isSignificantLength = original.length > 50;
|
|
21
|
+
if (isTooLong && isSignificantLength) errors.push(`Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`);
|
|
22
|
+
const originalLines = original.split("\n").length;
|
|
23
|
+
const translatedLines = translated.split("\n").length;
|
|
24
|
+
if (originalLines > 5) {
|
|
25
|
+
if (translatedLines < originalLines * .4) errors.push(`Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`);
|
|
26
|
+
}
|
|
27
|
+
if (errors.length > 0) {
|
|
28
|
+
logger(`Validation Failed: ${errors.join(", ")}`);
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
return true;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Clean common AI artifacts
|
|
35
|
+
*/
|
|
36
|
+
const sanitizeChunk = (translated, original) => {
|
|
37
|
+
let cleaned = translated;
|
|
38
|
+
const match = cleaned.match(/^```(?:markdown|md|txt)?\n([\s\S]*?)\n```$/i);
|
|
39
|
+
if (match) cleaned = match[1];
|
|
40
|
+
if (!original.startsWith("\n") && cleaned.startsWith("\n")) cleaned = cleaned.replace(/^\n+/, "");
|
|
41
|
+
if (!original.startsWith(" ") && cleaned.startsWith(" ")) cleaned = cleaned.trimStart();
|
|
42
|
+
return cleaned;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { sanitizeChunk, validateTranslation };
|
|
6
47
|
//# sourceMappingURL=validation.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/translateDoc/validation.ts"],"sourcesContent":["import type { Logger } from '@intlayer/config/logger';\n\n/**\n * Validates that the translated content matches the structure of the original.\n * Throws an error if a mismatch is found, triggering a retry.\n */\nexport const validateTranslation = (\n original: string,\n translated: string,\n logger: Logger\n): boolean => {\n const errors: string[] = [];\n\n // YAML Frontmatter Integrity (CRITICAL)\n if (original.trimStart().startsWith('---')) {\n if (!translated.trimStart().startsWith('---')) {\n errors.push(\n 'YAML Frontmatter missing: Input starts with \"---\", output does not.'\n );\n }\n const originalDashes = (original.match(/^---$/gm) || []).length;\n const translatedDashes = (translated.match(/^---$/gm) || []).length;\n if (originalDashes >= 2 && translatedDashes < 2) {\n errors.push(\n 'YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.'\n );\n }\n }\n\n // Code Fence Check\n const fenceRegex = /^\\s*```/gm;\n const originalFences = (original.match(fenceRegex) || []).length;\n const translatedFences = (translated.match(fenceRegex) || []).length;\n\n if (originalFences !== translatedFences) {\n errors.push(\n `Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`\n );\n }\n\n // Length/Duplication Check\n const ratio = translated.length / (original.length || 1);\n const isTooLong = ratio > 2.5;\n const isSignificantLength = original.length > 50;\n\n if (isTooLong && isSignificantLength) {\n errors.push(\n `Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`\n );\n }\n\n // Line Count Heuristic\n const originalLines = original.split('\\n').length;\n const translatedLines = translated.split('\\n').length;\n\n if (originalLines > 5) {\n if (translatedLines < originalLines * 0.4) {\n errors.push(\n `Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`\n );\n }\n }\n\n if (errors.length > 0) {\n logger(`Validation Failed: ${errors.join(', ')}`);\n return false;\n }\n\n return true;\n};\n\n/**\n * Clean common AI artifacts\n */\nexport const sanitizeChunk = (translated: string, original: string): string => {\n let cleaned = translated;\n const wrapRegex = /^```(?:markdown|md|txt)?\\n([\\s\\S]*?)\\n```$/i;\n const match = cleaned.match(wrapRegex);\n if (match) cleaned = match[1];\n\n if (!original.startsWith('\\n') && cleaned.startsWith('\\n')) {\n cleaned = cleaned.replace(/^\\n+/, '');\n }\n if (!original.startsWith(' ') && cleaned.startsWith(' ')) {\n cleaned = cleaned.trimStart();\n }\n return cleaned;\n};\n"],"mappings":"AAMA,MAAa,
|
|
1
|
+
{"version":3,"file":"validation.mjs","names":[],"sources":["../../../src/translateDoc/validation.ts"],"sourcesContent":["import type { Logger } from '@intlayer/config/logger';\n\n/**\n * Validates that the translated content matches the structure of the original.\n * Throws an error if a mismatch is found, triggering a retry.\n */\nexport const validateTranslation = (\n original: string,\n translated: string,\n logger: Logger\n): boolean => {\n const errors: string[] = [];\n\n // YAML Frontmatter Integrity (CRITICAL)\n if (original.trimStart().startsWith('---')) {\n if (!translated.trimStart().startsWith('---')) {\n errors.push(\n 'YAML Frontmatter missing: Input starts with \"---\", output does not.'\n );\n }\n const originalDashes = (original.match(/^---$/gm) || []).length;\n const translatedDashes = (translated.match(/^---$/gm) || []).length;\n if (originalDashes >= 2 && translatedDashes < 2) {\n errors.push(\n 'YAML Frontmatter unclosed: Input has closing \"---\", output is missing it.'\n );\n }\n }\n\n // Code Fence Check\n const fenceRegex = /^\\s*```/gm;\n const originalFences = (original.match(fenceRegex) || []).length;\n const translatedFences = (translated.match(fenceRegex) || []).length;\n\n if (originalFences !== translatedFences) {\n errors.push(\n `Code fence mismatch: Input has ${originalFences}, output has ${translatedFences}`\n );\n }\n\n // Length/Duplication Check\n const ratio = translated.length / (original.length || 1);\n const isTooLong = ratio > 2.5;\n const isSignificantLength = original.length > 50;\n\n if (isTooLong && isSignificantLength) {\n errors.push(\n `Length deviation: Output is ${translated.length} chars vs Input ${original.length} (${ratio.toFixed(1)}x). Likely included context.`\n );\n }\n\n // Line Count Heuristic\n const originalLines = original.split('\\n').length;\n const translatedLines = translated.split('\\n').length;\n\n if (originalLines > 5) {\n if (translatedLines < originalLines * 0.4) {\n errors.push(\n `Line count deviation: Output has ${translatedLines} lines, Input has ${originalLines}. Likely content deletion.`\n );\n }\n }\n\n if (errors.length > 0) {\n logger(`Validation Failed: ${errors.join(', ')}`);\n return false;\n }\n\n return true;\n};\n\n/**\n * Clean common AI artifacts\n */\nexport const sanitizeChunk = (translated: string, original: string): string => {\n let cleaned = translated;\n const wrapRegex = /^```(?:markdown|md|txt)?\\n([\\s\\S]*?)\\n```$/i;\n const match = cleaned.match(wrapRegex);\n if (match) cleaned = match[1];\n\n if (!original.startsWith('\\n') && cleaned.startsWith('\\n')) {\n cleaned = cleaned.replace(/^\\n+/, '');\n }\n if (!original.startsWith(' ') && cleaned.startsWith(' ')) {\n cleaned = cleaned.trimStart();\n }\n return cleaned;\n};\n"],"mappings":";;;;;AAMA,MAAa,uBACX,UACA,YACA,WACY;CACZ,MAAM,SAAmB,EAAE;AAG3B,KAAI,SAAS,WAAW,CAAC,WAAW,MAAM,EAAE;AAC1C,MAAI,CAAC,WAAW,WAAW,CAAC,WAAW,MA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