@intlayer/cli 9.2.0 → 9.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -24
- package/dist/cjs/IntlayerEventListener.cjs +2 -6
- package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/_virtual/_utils_asset.cjs +2 -1
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/auth/sessionToken.cjs.map +1 -1
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/bundle.cjs +0 -1
- package/dist/cjs/bundle.cjs.map +1 -1
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/editor.cjs +3 -1
- package/dist/cjs/editor.cjs.map +1 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/deepMergeContent.cjs +0 -1
- package/dist/cjs/fill/deepMergeContent.cjs.map +1 -1
- package/dist/cjs/fill/extractTranslatableContent.cjs +0 -1
- package/dist/cjs/fill/extractTranslatableContent.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +4 -2
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +4 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs +0 -1
- package/dist/cjs/fill/getAvailableLocalesInDictionary.cjs.map +1 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs +0 -1
- package/dist/cjs/fill/getFilterMissingContentPerLocale.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +7 -6
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/init.cjs +3 -2
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initBuildOptimization.cjs.map +1 -1
- package/dist/cjs/initCompiler.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs +2 -1
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs +2 -1
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +2 -1
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +4 -2
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +4 -2
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocLog.cjs +6 -3
- package/dist/cjs/reviewDoc/reviewDocLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocProgress.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocSynthesis.cjs.map +1 -1
- package/dist/cjs/scan.cjs +2 -1
- package/dist/cjs/scan.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +3 -2
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +6 -3
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/translateDoc/validation.cjs +0 -1
- package/dist/cjs/translateDoc/validation.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs +0 -1
- package/dist/cjs/utils/checkConfigConsistency.cjs.map +1 -1
- package/dist/cjs/utils/checkFileModifiedRange.cjs +3 -2
- package/dist/cjs/utils/checkFileModifiedRange.cjs.map +1 -1
- package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
- package/dist/cjs/utils/chunkInference.cjs.map +1 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs +0 -1
- package/dist/cjs/utils/fixChunkStartEndChars.cjs.map +1 -1
- package/dist/cjs/utils/formatLineRanges.cjs +0 -1
- package/dist/cjs/utils/formatLineRanges.cjs.map +1 -1
- package/dist/cjs/utils/formatTimeDiff.cjs +0 -1
- package/dist/cjs/utils/formatTimeDiff.cjs.map +1 -1
- package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs +2 -1
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
- package/dist/cjs/utils/listSpecialChars.cjs +0 -1
- package/dist/cjs/utils/listSpecialChars.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/utils/openBrowser.cjs.map +1 -1
- package/dist/cjs/utils/selectCmsEnvironment.cjs +2 -1
- package/dist/cjs/utils/selectCmsEnvironment.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/IntlayerEventListener.mjs +2 -6
- package/dist/esm/IntlayerEventListener.mjs.map +1 -1
- package/dist/esm/_virtual/_utils_asset.mjs +2 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/editor.mjs +3 -1
- package/dist/esm/editor.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +4 -2
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +4 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +7 -6
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/init.mjs +3 -2
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initSkills.mjs +2 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs +2 -1
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/push/push.mjs +2 -1
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +4 -2
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +4 -2
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocLog.mjs +6 -3
- package/dist/esm/reviewDoc/reviewDocLog.mjs.map +1 -1
- package/dist/esm/scan.mjs +2 -1
- package/dist/esm/scan.mjs.map +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs +3 -2
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +6 -3
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/utils/checkFileModifiedRange.mjs +3 -2
- package/dist/esm/utils/checkFileModifiedRange.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs +2 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/selectCmsEnvironment.mjs +2 -1
- package/dist/esm/utils/selectCmsEnvironment.mjs.map +1 -1
- package/package.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push.mjs","names":[],"sources":["../../../src/push/push.ts"],"sourcesContent":["import * as fsPromises from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/engine/build';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n logConfigDetails,\n} from '@intlayer/engine/cli';\nimport { formatPath, parallelize } from '@intlayer/engine/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PushLogger, type PushStatus } from '../pushLog';\nimport { checkCMSAuth, getAuthenticatedAPI } from '../utils/checkAccess';\nimport { selectCmsEnvironment } from '../utils/selectCmsEnvironment';\n\ntype PushOptions = {\n deleteLocaleDictionary?: boolean;\n keepLocaleDictionary?: boolean;\n dictionaries?: string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\ntype DictionariesStatus = {\n dictionary: Dictionary;\n status:\n | 'pending'\n | 'pushing'\n | 'modified'\n | 'pushed'\n | 'up-to-date'\n | 'unknown'\n | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n// Print per-dictionary summary similar to loadDictionaries\nconst statusIconsAndColors = {\n pushed: { icon: '✔', color: ANSIColors.GREEN },\n modified: { icon: '✔', color: ANSIColors.GREEN },\n 'up-to-date': { icon: '=', color: ANSIColors.GREY },\n error: { icon: '✖', color: ANSIColors.RED },\n default: { icon: '⏲', color: ANSIColors.BLUE },\n};\n\nconst getIconAndColor = (status: DictionariesStatus['status']) => {\n return (\n statusIconsAndColors[status as keyof typeof statusIconsAndColors] ??\n statusIconsAndColors.default\n );\n};\n\n/**\n * Get all local dictionaries and push them simultaneously.\n */\nexport const push = async (options?: PushOptions): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\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 try {\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = await getAuthenticatedAPI(config);\n\n await selectCmsEnvironment(\n options?.configOptions?.env,\n intlayerAPI,\n config\n );\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n const allDictionaries = Object.values(unmergedDictionariesRecord).flat();\n\n const customLocations = Array.from(\n new Set(\n allDictionaries\n .map((dictionary) => dictionary.location)\n .filter(\n (location) =>\n location && !['remote', 'local', 'hybrid'].includes(location)\n )\n )\n ) as string[];\n\n // Include all custom locations automatically — no interactive prompt needed.\n const selectedCustomLocations: string[] = customLocations;\n\n let dictionaries: Dictionary[] = allDictionaries.filter((dictionary) => {\n const location =\n dictionary.location ?? config.dictionary?.location ?? 'local';\n\n return (\n location === 'remote' ||\n location === 'hybrid' ||\n selectedCustomLocations.includes(location)\n );\n });\n\n // Check if the dictionaries list is empty after filtering by location\n if (dictionaries.length === 0) {\n appLogger(\n `No dictionaries found to push. Only dictionaries with location ${colorize('remote', ANSIColors.BLUE, ANSIColors.RESET)}, ${colorize('hybrid', ANSIColors.BLUE, ANSIColors.RESET)} or selected custom locations are pushed.`,\n { level: 'warn' }\n );\n appLogger(\n `You can set the location in your dictionary file (e.g. ${colorize(\"{ key: 'my-key', location: 'hybrid', ... }\", ANSIColors.BLUE, ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${colorize(\"{ dictionary: { location: 'hybrid' } }\", ANSIColors.BLUE, ANSIColors.RESET)}).`,\n { level: 'info' }\n );\n return;\n }\n\n const existingDictionariesKeys: string[] = Object.keys(\n unmergedDictionariesRecord\n );\n\n if (options?.dictionaries) {\n // Check if the provided dictionaries exist\n const noneExistingDictionariesOption = options.dictionaries.filter(\n (dictionaryId) => !existingDictionariesKeys.includes(dictionaryId)\n );\n\n if (noneExistingDictionariesOption.length > 0) {\n appLogger(\n `The following dictionaries do not exist: ${noneExistingDictionariesOption.join(\n ', '\n )} and have been ignored.`,\n {\n level: 'error',\n }\n );\n }\n\n // Filter the dictionaries from the provided list of IDs\n dictionaries = dictionaries.filter((dictionary) =>\n options.dictionaries?.includes(dictionary.key)\n );\n }\n\n if (options?.gitOptions) {\n const gitFiles = await listGitFiles(options.gitOptions);\n\n dictionaries = dictionaries.filter((dictionary) =>\n gitFiles.includes(\n join(config.system.baseDir, dictionary.filePath ?? '')\n )\n );\n }\n\n // Check if the dictionaries list is empty\n if (dictionaries.length === 0) {\n appLogger('No local dictionaries found', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Pushing dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = dictionaries.map(\n (dictionary) => ({\n dictionary,\n status: 'pending',\n })\n );\n\n // Initialize aggregated logger similar to loadDictionaries\n const logger = new PushLogger();\n logger.update(\n dictionariesStatuses.map<PushStatus>((s) => ({\n dictionaryKey: s.dictionary.key,\n status: 'pending',\n }))\n );\n\n const successfullyPushedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n statusObj.status = 'pushing';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushing' },\n ]);\n\n try {\n const pushResult = await intlayerAPI.dictionary.pushDictionaries([\n statusObj.dictionary,\n ]);\n\n const updatedDictionaries = pushResult.data?.updatedDictionaries ?? [];\n const newDictionaries = pushResult.data?.newDictionaries ?? [];\n const upToDateDictionaries =\n pushResult.data?.upToDateDictionaries ?? [];\n\n const allDictionaries = [\n ...updatedDictionaries,\n ...newDictionaries,\n ...upToDateDictionaries,\n ];\n\n for (const remoteDictionaryData of allDictionaries) {\n const localDictionary = unmergedDictionariesRecord[\n remoteDictionaryData.key\n ]?.find(\n (dictionary) => dictionary.localId === remoteDictionaryData.localId\n );\n\n if (!localDictionary) continue;\n\n await writeContentDeclaration(\n { ...localDictionary, id: remoteDictionaryData.id },\n config\n );\n }\n\n if (\n updatedDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'modified';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'modified' },\n ]);\n } else if (\n newDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'pushed';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushed' },\n ]);\n } else if (\n upToDateDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'up-to-date';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'up-to-date' },\n ]);\n } else {\n statusObj.status = 'unknown';\n }\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error pushing dictionary ${statusObj.dictionary.key}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with a concurrency limit (reuse parallelize)\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n for (const dictionaryStatus of dictionariesStatuses) {\n const { icon, color } = getIconAndColor(dictionaryStatus.status);\n appLogger(\n ` - ${colorizeKey(dictionaryStatus.dictionary.key)} ${ANSIColors.GREY}[${color}${icon} ${dictionaryStatus.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n\n // Handle delete or keep options\n const deleteOption = options?.deleteLocaleDictionary;\n const keepOption = options?.keepLocaleDictionary;\n\n if (deleteOption && keepOption) {\n throw new Error(\n 'Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.'\n );\n }\n\n if (deleteOption) {\n // Delete only the successfully pushed dictionaries\n await deleteLocalDictionaries(successfullyPushedDictionaries, options);\n } else if (keepOption) {\n // Do nothing, keep the local dictionaries\n } else {\n // Ask the user\n const remoteDictionaries = successfullyPushedDictionaries.filter(\n (dictionary) => dictionary.location === 'remote'\n );\n const remoteDictionariesKeys = remoteDictionaries.map(\n (dictionary) => dictionary.key\n );\n\n if (remoteDictionaries.length > 0) {\n const { confirm, isCancel } = await import('@clack/prompts');\n\n const shouldDelete = await confirm({\n message: `Do you want to delete the local dictionaries that were successfully pushed? ${colorize('(Dictionaries:', ANSIColors.GREY, ANSIColors.RESET)} ${colorizeKey(remoteDictionariesKeys)}${colorize(')', ANSIColors.GREY, ANSIColors.RESET)}`,\n initialValue: false,\n });\n\n if (isCancel(shouldDelete)) {\n return;\n }\n\n if (shouldDelete) {\n await deleteLocalDictionaries(remoteDictionaries, options);\n }\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n\nconst deleteLocalDictionaries = async (\n dictionariesToDelete: Dictionary[],\n options?: PushOptions\n): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n // Use a Set to collect all unique file paths\n const filePathsSet: Set<string> = new Set();\n\n for (const dictionary of dictionariesToDelete) {\n const { filePath } = dictionary;\n\n if (!filePath) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} does not have a file path`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n filePathsSet.add(filePath);\n }\n\n for (const filePath of filePathsSet) {\n try {\n const stats = await fsPromises.lstat(filePath);\n\n if (stats.isFile()) {\n await fsPromises.unlink(filePath);\n appLogger(`Deleted file ${formatPath(filePath)}`, {});\n } else if (stats.isDirectory()) {\n appLogger(`Path is a directory ${formatPath(filePath)}, skipping.`, {});\n } else {\n appLogger(\n `Unknown file type for ${formatPath(filePath)}, skipping.`,\n {}\n );\n }\n } catch (err) {\n appLogger(`Error deleting ${formatPath(filePath)}: ${err}`, {\n level: 'error',\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAgDA,MAAM,uBAAuB;CAC3B,QAAQ;EAAE,MAAM;EAAK,OAAO,WAAW;CAAM;CAC7C,UAAU;EAAE,MAAM;EAAK,OAAO,WAAW;CAAM;CAC/C,cAAc;EAAE,MAAM;EAAK,OAAO,WAAW;CAAK;CAClD,OAAO;EAAE,MAAM;EAAK,OAAO,WAAW;CAAI;CAC1C,SAAS;EAAE,MAAM;EAAK,OAAO,WAAW;CAAK;AAC/C;AAEA,MAAM,mBAAmB,WAAyC;CAChE,OACE,qBAAqB,WACrB,qBAAqB;AAEzB;;;;AAKA,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,SAAS,iBAAiB,SAAS,aAAa;CACtD,iBAAiB,SAAS,aAAa;CAEvC,MAAM,YAAY,aAAa,MAAM;CAErC,IAAI,SAAS,UAAU,MACrB,MAAM,gBAAgB,QAAQ,EAAE,UAAU,KAAK,CAAC;MAC3C,IAAI,OAAO,SAAS,UAAU,aACnC,MAAM,gBAAgB,MAAM;CAG9B,IAAI;EAGF,IAAI,CAAC,MAFoB,aAAa,MAAM,GAE3B;EAEjB,MAAM,cAAc,MAAM,oBAAoB,MAAM;EAEpD,MAAM,qBACJ,SAAS,eAAe,KACxB,aACA,MACF;EAEA,MAAM,6BAA6B,wBAAwB,MAAM;EACjE,MAAM,kBAAkB,OAAO,OAAO,0BAA0B,CAAC,CAAC,KAAK;EAcvE,MAAM,0BAZkB,MAAM,KAC5B,IAAI,IACF,gBACG,KAAK,eAAe,WAAW,QAAQ,CAAC,CACxC,QACE,aACC,YAAY,CAAC;GAAC;GAAU;GAAS;EAAQ,CAAC,CAAC,SAAS,QAAQ,CAChE,CACJ,CAIsD;EAExD,IAAI,eAA6B,gBAAgB,QAAQ,eAAe;GACtE,MAAM,WACJ,WAA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;EACd,UAAU,OAAO,EACf,OAAO,QACT,CAAC;CACH;AACF;AAEA,MAAM,0BAA0B,OAC9B,sBACA,YACkB;CAElB,MAAM,YAAY,aADH,iBAAiB,SAAS,aACL,CAAC;CAGrC,MAAM,+BAA4B,IAAI,IAAI;CAE1C,KAAK,MAAM,cAAc,sBAAsB;EAC7C,MAAM,EAAE,aAAa;EAErB,IAAI,CAAC,UAAU;GACb,UACE,cAAc,YAAY,WAAW,GAAG,EAAE,6BAC1C,EACE,OAAO,QACT,CACF;GACA;EACF;EAEA,aAAa,IAAI,QAAQ;CAC3B;CAEA,KAAK,MAAM,YAAY,cACrB,IAAI;EACF,MAAM,QAAQ,MAAM,WAAW,MAAM,QAAQ;EAE7C,IAAI,MAAM,OAAO,GAAG;GAClB,MAAM,WAAW,OAAO,QAAQ;GAChC,UAAU,gBAAgB,WAAW,QAAQ,KAAK,CAAC,CAAC;EACtD,OAAO,IAAI,MAAM,YAAY,GAC3B,UAAU,uBAAuB,WAAW,QAAQ,EAAE,cAAc,CAAC,CAAC;OAEtE,UACE,yBAAyB,WAAW,QAAQ,EAAE,cAC9C,CAAC,CACH;CAEJ,SAAS,KAAK;EACZ,UAAU,kBAAkB,WAAW,QAAQ,EAAE,IAAI,OAAO,EAC1D,OAAO,QACT,CAAC;CACH;AAEJ"}
|
|
1
|
+
{"version":3,"file":"push.mjs","names":[],"sources":["../../../src/push/push.ts"],"sourcesContent":["import * as fsPromises from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/engine/build';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n logConfigDetails,\n} from '@intlayer/engine/cli';\nimport { formatPath, parallelize } from '@intlayer/engine/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PushLogger, type PushStatus } from '../pushLog';\nimport { checkCMSAuth, getAuthenticatedAPI } from '../utils/checkAccess';\nimport { selectCmsEnvironment } from '../utils/selectCmsEnvironment';\n\ntype PushOptions = {\n deleteLocaleDictionary?: boolean;\n keepLocaleDictionary?: boolean;\n dictionaries?: string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\ntype DictionariesStatus = {\n dictionary: Dictionary;\n status:\n | 'pending'\n | 'pushing'\n | 'modified'\n | 'pushed'\n | 'up-to-date'\n | 'unknown'\n | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n// Print per-dictionary summary similar to loadDictionaries\nconst statusIconsAndColors = {\n pushed: { icon: '✔', color: ANSIColors.GREEN },\n modified: { icon: '✔', color: ANSIColors.GREEN },\n 'up-to-date': { icon: '=', color: ANSIColors.GREY },\n error: { icon: '✖', color: ANSIColors.RED },\n default: { icon: '⏲', color: ANSIColors.BLUE },\n};\n\nconst getIconAndColor = (status: DictionariesStatus['status']) => {\n return (\n statusIconsAndColors[status as keyof typeof statusIconsAndColors] ??\n statusIconsAndColors.default\n );\n};\n\n/**\n * Get all local dictionaries and push them simultaneously.\n */\nexport const push = async (options?: PushOptions): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\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 try {\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = await getAuthenticatedAPI(config);\n\n await selectCmsEnvironment(\n options?.configOptions?.env,\n intlayerAPI,\n config\n );\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n const allDictionaries = Object.values(unmergedDictionariesRecord).flat();\n\n const customLocations = Array.from(\n new Set(\n allDictionaries\n .map((dictionary) => dictionary.location)\n .filter(\n (location) =>\n location && !['remote', 'local', 'hybrid'].includes(location)\n )\n )\n ) as string[];\n\n // Include all custom locations automatically — no interactive prompt needed.\n const selectedCustomLocations: string[] = customLocations;\n\n let dictionaries: Dictionary[] = allDictionaries.filter((dictionary) => {\n const location =\n dictionary.location ?? config.dictionary?.location ?? 'local';\n\n return (\n location === 'remote' ||\n location === 'hybrid' ||\n selectedCustomLocations.includes(location)\n );\n });\n\n // Check if the dictionaries list is empty after filtering by location\n if (dictionaries.length === 0) {\n appLogger(\n `No dictionaries found to push. Only dictionaries with location ${colorize('remote', ANSIColors.BLUE, ANSIColors.RESET)}, ${colorize('hybrid', ANSIColors.BLUE, ANSIColors.RESET)} or selected custom locations are pushed.`,\n { level: 'warn' }\n );\n appLogger(\n `You can set the location in your dictionary file (e.g. ${colorize(\"{ key: 'my-key', location: 'hybrid', ... }\", ANSIColors.BLUE, ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${colorize(\"{ dictionary: { location: 'hybrid' } }\", ANSIColors.BLUE, ANSIColors.RESET)}).`,\n { level: 'info' }\n );\n return;\n }\n\n const existingDictionariesKeys: string[] = Object.keys(\n unmergedDictionariesRecord\n );\n\n if (options?.dictionaries) {\n // Check if the provided dictionaries exist\n const noneExistingDictionariesOption = options.dictionaries.filter(\n (dictionaryId) => !existingDictionariesKeys.includes(dictionaryId)\n );\n\n if (noneExistingDictionariesOption.length > 0) {\n appLogger(\n `The following dictionaries do not exist: ${noneExistingDictionariesOption.join(\n ', '\n )} and have been ignored.`,\n {\n level: 'error',\n }\n );\n }\n\n // Filter the dictionaries from the provided list of IDs\n dictionaries = dictionaries.filter((dictionary) =>\n options.dictionaries?.includes(dictionary.key)\n );\n }\n\n if (options?.gitOptions) {\n const gitFiles = await listGitFiles(options.gitOptions);\n\n dictionaries = dictionaries.filter((dictionary) =>\n gitFiles.includes(\n join(config.system.baseDir, dictionary.filePath ?? '')\n )\n );\n }\n\n // Check if the dictionaries list is empty\n if (dictionaries.length === 0) {\n appLogger('No local dictionaries found', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Pushing dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = dictionaries.map(\n (dictionary) => ({\n dictionary,\n status: 'pending',\n })\n );\n\n // Initialize aggregated logger similar to loadDictionaries\n const logger = new PushLogger();\n logger.update(\n dictionariesStatuses.map<PushStatus>((s) => ({\n dictionaryKey: s.dictionary.key,\n status: 'pending',\n }))\n );\n\n const successfullyPushedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n statusObj.status = 'pushing';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushing' },\n ]);\n\n try {\n const pushResult = await intlayerAPI.dictionary.pushDictionaries([\n statusObj.dictionary,\n ]);\n\n const updatedDictionaries = pushResult.data?.updatedDictionaries ?? [];\n const newDictionaries = pushResult.data?.newDictionaries ?? [];\n const upToDateDictionaries =\n pushResult.data?.upToDateDictionaries ?? [];\n\n const allDictionaries = [\n ...updatedDictionaries,\n ...newDictionaries,\n ...upToDateDictionaries,\n ];\n\n for (const remoteDictionaryData of allDictionaries) {\n const localDictionary = unmergedDictionariesRecord[\n remoteDictionaryData.key\n ]?.find(\n (dictionary) => dictionary.localId === remoteDictionaryData.localId\n );\n\n if (!localDictionary) continue;\n\n await writeContentDeclaration(\n { ...localDictionary, id: remoteDictionaryData.id },\n config\n );\n }\n\n if (\n updatedDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'modified';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'modified' },\n ]);\n } else if (\n newDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'pushed';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushed' },\n ]);\n } else if (\n upToDateDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'up-to-date';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'up-to-date' },\n ]);\n } else {\n statusObj.status = 'unknown';\n }\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error pushing dictionary ${statusObj.dictionary.key}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with a concurrency limit (reuse parallelize)\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n for (const dictionaryStatus of dictionariesStatuses) {\n const { icon, color } = getIconAndColor(dictionaryStatus.status);\n appLogger(\n ` - ${colorizeKey(dictionaryStatus.dictionary.key)} ${ANSIColors.GREY}[${color}${icon} ${dictionaryStatus.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n\n // Handle delete or keep options\n const deleteOption = options?.deleteLocaleDictionary;\n const keepOption = options?.keepLocaleDictionary;\n\n if (deleteOption && keepOption) {\n throw new Error(\n 'Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.'\n );\n }\n\n if (deleteOption) {\n // Delete only the successfully pushed dictionaries\n await deleteLocalDictionaries(successfullyPushedDictionaries, options);\n } else if (keepOption) {\n // Do nothing, keep the local dictionaries\n } else {\n // Ask the user\n const remoteDictionaries = successfullyPushedDictionaries.filter(\n (dictionary) => dictionary.location === 'remote'\n );\n const remoteDictionariesKeys = remoteDictionaries.map(\n (dictionary) => dictionary.key\n );\n\n if (remoteDictionaries.length > 0) {\n const { confirm, isCancel } = await import('@clack/prompts');\n\n const shouldDelete = await confirm({\n message: `Do you want to delete the local dictionaries that were successfully pushed? ${colorize('(Dictionaries:', ANSIColors.GREY, ANSIColors.RESET)} ${colorizeKey(remoteDictionariesKeys)}${colorize(')', ANSIColors.GREY, ANSIColors.RESET)}`,\n initialValue: false,\n });\n\n if (isCancel(shouldDelete)) {\n return;\n }\n\n if (shouldDelete) {\n await deleteLocalDictionaries(remoteDictionaries, options);\n }\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n\nconst deleteLocalDictionaries = async (\n dictionariesToDelete: Dictionary[],\n options?: PushOptions\n): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n // Use a Set to collect all unique file paths\n const filePathsSet: Set<string> = new Set();\n\n for (const dictionary of dictionariesToDelete) {\n const { filePath } = dictionary;\n\n if (!filePath) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} does not have a file path`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n filePathsSet.add(filePath);\n }\n\n for (const filePath of filePathsSet) {\n try {\n const stats = await fsPromises.lstat(filePath);\n\n if (stats.isFile()) {\n await fsPromises.unlink(filePath);\n appLogger(`Deleted file ${formatPath(filePath)}`, {});\n } else if (stats.isDirectory()) {\n appLogger(`Path is a directory ${formatPath(filePath)}, skipping.`, {});\n } else {\n appLogger(\n `Unknown file type for ${formatPath(filePath)}, skipping.`,\n {}\n );\n }\n } catch (err) {\n appLogger(`Error deleting ${formatPath(filePath)}: ${err}`, {\n level: 'error',\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAgDA,MAAM,uBAAuB;CAC3B,QAAQ;EAAE,MAAM;EAAK,OAAO,WAAW;CAAM;CAC7C,UAAU;EAAE,MAAM;EAAK,OAAO,WAAW;CAAM;CAC/C,cAAc;EAAE,MAAM;EAAK,OAAO,WAAW;CAAK;CAClD,OAAO;EAAE,MAAM;EAAK,OAAO,WAAW;CAAI;CAC1C,SAAS;EAAE,MAAM;EAAK,OAAO,WAAW;CAAK;AA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rB,IAAI;EACF,MAAM,QAAQ,MAAM,WAAW,MAAM,QAAQ;EAE7C,IAAI,MAAM,OAAO,GAAG;GAClB,MAAM,WAAW,OAAO,QAAQ;GAChC,UAAU,gBAAgB,WAAW,QAAQ,KAAK,CAAC,CAAC;EACtD,OAAO,IAAI,MAAM,YAAY,GAC3B,UAAU,uBAAuB,WAAW,QAAQ,EAAE,cAAc,CAAC,CAAC;OAEtE,UACE,yBAAyB,WAAW,QAAQ,EAAE,cAC9C,CAAC,CACH;CAEJ,SAAS,KAAK;EACZ,UAAU,kBAAkB,WAAW,QAAQ,EAAE,IAAI,OAAO,EAC1D,OAAO,QACT,CAAC;CACH;AAEJ"}
|
|
@@ -98,9 +98,11 @@ const reviewDoc = async ({ docPattern, locales, excludedGlobPattern, baseLocale,
|
|
|
98
98
|
const gitChangedLines = await listGitLines(absoluteBaseFilePath, gitOptions);
|
|
99
99
|
changedLines = gitChangedLines;
|
|
100
100
|
logProgress(`Changed lines (${formatLocale(baseLocale)}): ${formatLineRanges(gitChangedLines)}`);
|
|
101
|
+
const baseText = await readFile(absoluteBaseFilePath, "utf-8").catch(() => "");
|
|
102
|
+
const targetText = existsSync(outputFilePath) ? await readFile(outputFilePath, "utf-8").catch(() => "") : "";
|
|
101
103
|
const { blocks } = buildReviewReport({
|
|
102
|
-
baseText
|
|
103
|
-
targetText
|
|
104
|
+
baseText,
|
|
105
|
+
targetText,
|
|
104
106
|
changedLines: gitChangedLines
|
|
105
107
|
});
|
|
106
108
|
const correspondingTargetLines = blocks.flatMap((block) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewDoc.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDoc.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n listGitLines,\n logConfigDetails,\n} from '@intlayer/engine/cli';\nimport {\n buildReviewReport,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath, parallelize } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { formatLineRanges } from '../utils/formatLineRanges';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { type AIClient, setupAI } from '../utils/setupAI';\nimport { reviewFileBlockAware } from './reviewDocBlockAware';\nimport { buildFileReviewReport, logReviewFileBlocks } from './reviewDocLog';\nimport { createReviewProgressLogger } from './reviewDocProgress';\nimport {\n formatReviewSynthesis,\n type ReviewFileResult,\n type ReviewOutcome,\n} from './reviewDocSynthesis';\n\n/**\n * How the review should be run.\n *\n * - `apply`: translate the diverging blocks with AI and write the target files.\n * - `report`: no AI. Log every block that needs attention (line numbers and\n * content, for both locales) so another agent can generate the translations.\n * - `synthesis`: no AI, no per-block output. Only log the final synthesis of the\n * documents that are up to date and the ones that still have blocks to edit.\n */\nexport type ReviewDocMode = 'apply' | 'report' | 'synthesis';\n\ntype ReviewDocOptions = {\n docPattern: string[];\n locales: Locale[];\n excludedGlobPattern: string[];\n baseLocale: Locale;\n aiOptions?: AIOptions;\n nbSimultaneousFileProcessed?: number;\n configOptions?: GetConfigurationOptions;\n customInstructions?: string;\n skipIfModifiedBefore?: number | string | Date;\n skipIfModifiedAfter?: number | string | Date;\n skipIfExists?: boolean;\n gitOptions?: ListGitFilesOptions;\n /** How the review should be run. Defaults to `apply`. See {@link ReviewDocMode}. */\n mode?: ReviewDocMode;\n};\n\n/**\n * Main audit function: scans all .md files in \"en/\" (unless you specified DOC_LIST),\n * then audits them to each locale in LOCALE_LIST.\n */\nexport const reviewDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed,\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n mode = 'apply',\n}: ReviewDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger({ log: { ...configuration.log, prefix: '' } });\n\n // The `report` and `synthesis` modes never call an AI, so the AI access\n // checks are skipped.\n let aiClient: AIClient | undefined;\n let aiConfig: AIConfig | undefined;\n\n if (mode === 'apply') {\n const aiResult = await setupAI(configuration, aiOptions);\n\n if (!aiResult?.hasAIAccess) return [];\n\n aiClient = aiResult.aiClient;\n aiConfig = aiResult.aiConfig;\n\n if (aiResult.isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return [];\n }\n }\n }\n\n if (nbSimultaneousFileProcessed && nbSimultaneousFileProcessed > 10) {\n appLogger(\n `Warning: nbSimultaneousFileProcessed is set to ${nbSimultaneousFileProcessed}, which is greater than 10. Setting it to 10.`\n );\n nbSimultaneousFileProcessed = 10; // Limit the number of simultaneous file processed to 10\n }\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n // OAuth handled by API proxy internally\n\n appLogger(`Base locale is ${formatLocale(baseLocale)}`);\n appLogger(\n `Reviewing ${colorizeNumber(locales.length)} locales: [ ${formatLocale(locales)} ]`\n );\n\n appLogger(`Reviewing ${colorizeNumber(docList.length)} files:`);\n appLogger(docList.map((path) => ` - ${formatPath(path)}\\n`));\n\n // In `synthesis` mode only the final recap is printed, so the per-file\n // progress logs are muted.\n const logProgress: typeof appLogger = (...content) => {\n if (mode === 'synthesis') return;\n appLogger(...content);\n };\n\n // Filled by every task, then rendered as the end-of-run synthesis.\n const reviewResults: ReviewFileResult[] = [];\n\n /** A document is up to date when no block has to be added, reviewed or removed. */\n const getOutcome = (summary: ReviewReportSummary): ReviewOutcome =>\n summary.review + summary.insertNew + summary.delete > 0\n ? 'toEdit'\n : 'upToDate';\n\n // Create all tasks to be processed\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n logProgress(\n `Reviewing file: ${formatPath(docPath)} to ${formatLocale(locale)}`\n );\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip if file exists and skipIfExists option is enabled\n if (skipIfExists && existsSync(outputFilePath)) {\n const relativePath = relative(\n configuration.system.baseDir,\n outputFilePath\n );\n logProgress(\n `${colorize('⊘', ANSIColors.YELLOW)} File ${formatPath(relativePath)} already exists, skipping.`\n );\n reviewResults.push({ docPath, locale, outcome: 'skipped' });\n return;\n }\n\n // Check modification range only if the file exists\n if (existsSync(outputFilePath)) {\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n logProgress(fileModificationData.message);\n reviewResults.push({ docPath, locale, outcome: 'skipped' });\n return;\n }\n } else if (skipIfModifiedBefore || skipIfModifiedAfter) {\n // Log if we intended to check modification time but couldn't because the file doesn't exist\n logProgress(\n `${colorize('!', ANSIColors.YELLOW)} File ${formatPath(outputFilePath)} does not exist, skipping modification date check.`\n );\n }\n\n let changedLines: number[] | undefined;\n // FIXED: Enable git optimization that was previously commented out\n if (gitOptions) {\n const gitChangedLines = await listGitLines(\n absoluteBaseFilePath,\n gitOptions\n );\n changedLines = gitChangedLines;\n\n // Report the base lines that changed, then the corresponding line span\n // in the target document — i.e. the blocks the alignment will actually\n // re-translate. `review` blocks are exactly the aligned base blocks the\n // changed lines touched, so their `targetLineRange` is the matching span\n // in the existing translation.\n logProgress(\n `Changed lines (${formatLocale(baseLocale)}): ${formatLineRanges(gitChangedLines)}`\n );\n\n const baseText = await readFile(absoluteBaseFilePath, 'utf-8').catch(\n () => ''\n );\n const targetText = existsSync(outputFilePath)\n ? await readFile(outputFilePath, 'utf-8').catch(() => '')\n : '';\n\n const { blocks } = buildReviewReport({\n baseText,\n targetText,\n changedLines: gitChangedLines,\n });\n\n const correspondingTargetLines = blocks.flatMap((block) => {\n if (block.action !== 'review' || !block.targetLineRange) return [];\n\n const { start, end } = block.targetLineRange;\n return Array.from(\n { length: end - start + 1 },\n (_unused, offset) => start + offset\n );\n });\n\n logProgress(\n `Corresponding block (${formatLocale(locale)}): ${formatLineRanges(correspondingTargetLines)}`\n );\n }\n\n if (mode !== 'apply') {\n const report = await buildFileReviewReport(\n absoluteBaseFilePath,\n outputFilePath,\n changedLines\n );\n\n if (mode === 'report') {\n logReviewFileBlocks(\n report,\n absoluteBaseFilePath,\n locale as Locale,\n baseLocale,\n configOptions\n );\n }\n\n reviewResults.push({\n docPath,\n locale,\n outcome: getOutcome(report.summary),\n summary: report.summary,\n });\n return;\n }\n\n const reviewSummary = await reviewFileBlockAware(\n absoluteBaseFilePath,\n outputFilePath,\n locale as Locale,\n baseLocale,\n aiOptions,\n configOptions,\n customInstructions,\n changedLines,\n aiClient,\n aiConfig\n );\n\n reviewResults.push({\n docPath,\n locale,\n outcome: getOutcome(reviewSummary),\n summary: reviewSummary,\n });\n })\n );\n\n // The per-file logs are muted in `synthesis` mode, so a progress line keeps\n // the run readable while every document is compared.\n const progressLogger = createReviewProgressLogger(allTasks.length);\n\n if (mode === 'synthesis') progressLogger.start();\n\n await parallelize(\n allTasks,\n async (task) => {\n await task();\n progressLogger.increment();\n },\n nbSimultaneousFileProcessed ?? 3\n );\n\n progressLogger.stop();\n\n const synthesis = formatReviewSynthesis(reviewResults, {\n hasAppliedChanges: mode === 'apply',\n });\n\n for (const line of synthesis.split('\\n')) {\n appLogger(line);\n }\n\n return reviewResults;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAa,YAAY,OAAO,EAC9B,YACA,SACA,qBACA,YACA,WACA,6BACA,eACA,oBACA,sBACA,qBACA,cACA,YACA,OAAO,cACe;CACtB,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,iBAAiB,aAAa;CAE9B,MAAM,YAAY,aAAa,EAAE,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAAE,CAAC;CAI5E,IAAI;CACJ,IAAI;CAEJ,IAAI,SAAS,SAAS;EACpB,MAAM,WAAW,MAAM,QAAQ,eAAe,SAAS;EAEvD,IAAI,CAAC,UAAU,aAAa,OAAO,CAAC;EAEpC,WAAW,SAAS;EACpB,WAAW,SAAS;EAEpB,IAAI,SAAS,cAAc,YAAY,UAAU;GAC/C,MAAM,EAAE,aAAa,UAAU,MAAM,SAAS,iBAAiB,QAAQ;GACvE,IAAI,CAAC,aAAa;IAChB,UAAU,GAAG,EAAE,GAAG,OAAO;IACzB,OAAO,CAAC;GACV;EACF;CACF;CAEA,IAAI,+BAA+B,8BAA8B,IAAI;EACnE,UACE,kDAAkD,4BAA4B,8CAChF;EACA,8BAA8B;CAChC;CAEA,IAAI,UAAoB,MAAM,GAAG,YAAY,EAC3C,QAAQ,oBACV,CAAC;CAED,IAAI,YAAY;EACd,MAAM,kBAAkB,MAAM,aAAa,UAAU;EAErD,IAAI,iBAIF,UAAU,QAAQ,QAAQ,SACxB,gBAAgB,MAAM,YAAY,KAAK,QAAQ,IAAI,GAAG,IAAI,MAAM,OAAO,CACzE;CAEJ;CAIA,UAAU,kBAAkB,aAAa,UAAU,GAAG;CACtD,UACE,aAAa,eAAe,QAAQ,MAAM,EAAE,cAAc,aAAa,OAAO,EAA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GhB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"reviewDoc.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDoc.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n listGitLines,\n logConfigDetails,\n} from '@intlayer/engine/cli';\nimport {\n buildReviewReport,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath, parallelize } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { formatLineRanges } from '../utils/formatLineRanges';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { type AIClient, setupAI } from '../utils/setupAI';\nimport { reviewFileBlockAware } from './reviewDocBlockAware';\nimport { buildFileReviewReport, logReviewFileBlocks } from './reviewDocLog';\nimport { createReviewProgressLogger } from './reviewDocProgress';\nimport {\n formatReviewSynthesis,\n type ReviewFileResult,\n type ReviewOutcome,\n} from './reviewDocSynthesis';\n\n/**\n * How the review should be run.\n *\n * - `apply`: translate the diverging blocks with AI and write the target files.\n * - `report`: no AI. Log every block that needs attention (line numbers and\n * content, for both locales) so another agent can generate the translations.\n * - `synthesis`: no AI, no per-block output. Only log the final synthesis of the\n * documents that are up to date and the ones that still have blocks to edit.\n */\nexport type ReviewDocMode = 'apply' | 'report' | 'synthesis';\n\ntype ReviewDocOptions = {\n docPattern: string[];\n locales: Locale[];\n excludedGlobPattern: string[];\n baseLocale: Locale;\n aiOptions?: AIOptions;\n nbSimultaneousFileProcessed?: number;\n configOptions?: GetConfigurationOptions;\n customInstructions?: string;\n skipIfModifiedBefore?: number | string | Date;\n skipIfModifiedAfter?: number | string | Date;\n skipIfExists?: boolean;\n gitOptions?: ListGitFilesOptions;\n /** How the review should be run. Defaults to `apply`. See {@link ReviewDocMode}. */\n mode?: ReviewDocMode;\n};\n\n/**\n * Main audit function: scans all .md files in \"en/\" (unless you specified DOC_LIST),\n * then audits them to each locale in LOCALE_LIST.\n */\nexport const reviewDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed,\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n mode = 'apply',\n}: ReviewDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger({ log: { ...configuration.log, prefix: '' } });\n\n // The `report` and `synthesis` modes never call an AI, so the AI access\n // checks are skipped.\n let aiClient: AIClient | undefined;\n let aiConfig: AIConfig | undefined;\n\n if (mode === 'apply') {\n const aiResult = await setupAI(configuration, aiOptions);\n\n if (!aiResult?.hasAIAccess) return [];\n\n aiClient = aiResult.aiClient;\n aiConfig = aiResult.aiConfig;\n\n if (aiResult.isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return [];\n }\n }\n }\n\n if (nbSimultaneousFileProcessed && nbSimultaneousFileProcessed > 10) {\n appLogger(\n `Warning: nbSimultaneousFileProcessed is set to ${nbSimultaneousFileProcessed}, which is greater than 10. Setting it to 10.`\n );\n nbSimultaneousFileProcessed = 10; // Limit the number of simultaneous file processed to 10\n }\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n // OAuth handled by API proxy internally\n\n appLogger(`Base locale is ${formatLocale(baseLocale)}`);\n appLogger(\n `Reviewing ${colorizeNumber(locales.length)} locales: [ ${formatLocale(locales)} ]`\n );\n\n appLogger(`Reviewing ${colorizeNumber(docList.length)} files:`);\n appLogger(docList.map((path) => ` - ${formatPath(path)}\\n`));\n\n // In `synthesis` mode only the final recap is printed, so the per-file\n // progress logs are muted.\n const logProgress: typeof appLogger = (...content) => {\n if (mode === 'synthesis') return;\n appLogger(...content);\n };\n\n // Filled by every task, then rendered as the end-of-run synthesis.\n const reviewResults: ReviewFileResult[] = [];\n\n /** A document is up to date when no block has to be added, reviewed or removed. */\n const getOutcome = (summary: ReviewReportSummary): ReviewOutcome =>\n summary.review + summary.insertNew + summary.delete > 0\n ? 'toEdit'\n : 'upToDate';\n\n // Create all tasks to be processed\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n logProgress(\n `Reviewing file: ${formatPath(docPath)} to ${formatLocale(locale)}`\n );\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip if file exists and skipIfExists option is enabled\n if (skipIfExists && existsSync(outputFilePath)) {\n const relativePath = relative(\n configuration.system.baseDir,\n outputFilePath\n );\n logProgress(\n `${colorize('⊘', ANSIColors.YELLOW)} File ${formatPath(relativePath)} already exists, skipping.`\n );\n reviewResults.push({ docPath, locale, outcome: 'skipped' });\n return;\n }\n\n // Check modification range only if the file exists\n if (existsSync(outputFilePath)) {\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n logProgress(fileModificationData.message);\n reviewResults.push({ docPath, locale, outcome: 'skipped' });\n return;\n }\n } else if (skipIfModifiedBefore || skipIfModifiedAfter) {\n // Log if we intended to check modification time but couldn't because the file doesn't exist\n logProgress(\n `${colorize('!', ANSIColors.YELLOW)} File ${formatPath(outputFilePath)} does not exist, skipping modification date check.`\n );\n }\n\n let changedLines: number[] | undefined;\n // FIXED: Enable git optimization that was previously commented out\n if (gitOptions) {\n const gitChangedLines = await listGitLines(\n absoluteBaseFilePath,\n gitOptions\n );\n changedLines = gitChangedLines;\n\n // Report the base lines that changed, then the corresponding line span\n // in the target document — i.e. the blocks the alignment will actually\n // re-translate. `review` blocks are exactly the aligned base blocks the\n // changed lines touched, so their `targetLineRange` is the matching span\n // in the existing translation.\n logProgress(\n `Changed lines (${formatLocale(baseLocale)}): ${formatLineRanges(gitChangedLines)}`\n );\n\n const baseText = await readFile(absoluteBaseFilePath, 'utf-8').catch(\n () => ''\n );\n const targetText = existsSync(outputFilePath)\n ? await readFile(outputFilePath, 'utf-8').catch(() => '')\n : '';\n\n const { blocks } = buildReviewReport({\n baseText,\n targetText,\n changedLines: gitChangedLines,\n });\n\n const correspondingTargetLines = blocks.flatMap((block) => {\n if (block.action !== 'review' || !block.targetLineRange) return [];\n\n const { start, end } = block.targetLineRange;\n return Array.from(\n { length: end - start + 1 },\n (_unused, offset) => start + offset\n );\n });\n\n logProgress(\n `Corresponding block (${formatLocale(locale)}): ${formatLineRanges(correspondingTargetLines)}`\n );\n }\n\n if (mode !== 'apply') {\n const report = await buildFileReviewReport(\n absoluteBaseFilePath,\n outputFilePath,\n changedLines\n );\n\n if (mode === 'report') {\n logReviewFileBlocks(\n report,\n absoluteBaseFilePath,\n locale as Locale,\n baseLocale,\n configOptions\n );\n }\n\n reviewResults.push({\n docPath,\n locale,\n outcome: getOutcome(report.summary),\n summary: report.summary,\n });\n return;\n }\n\n const reviewSummary = await reviewFileBlockAware(\n absoluteBaseFilePath,\n outputFilePath,\n locale as Locale,\n baseLocale,\n aiOptions,\n configOptions,\n customInstructions,\n changedLines,\n aiClient,\n aiConfig\n );\n\n reviewResults.push({\n docPath,\n locale,\n outcome: getOutcome(reviewSummary),\n summary: reviewSummary,\n });\n })\n );\n\n // The per-file logs are muted in `synthesis` mode, so a progress line keeps\n // the run readable while every document is compared.\n const progressLogger = createReviewProgressLogger(allTasks.length);\n\n if (mode === 'synthesis') progressLogger.start();\n\n await parallelize(\n allTasks,\n async (task) => {\n await task();\n progressLogger.increment();\n },\n nbSimultaneousFileProcessed ?? 3\n );\n\n progressLogger.stop();\n\n const synthesis = formatReviewSynthesis(reviewResults, {\n hasAppliedChanges: mode === 'apply',\n });\n\n for (const line of synthesis.split('\\n')) {\n appLogger(line);\n }\n\n return reviewResults;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAa,YAAY,OAAO,EAC9B,YACA,SACA,qBACA,YACA,WACA,6BACA,eACA,oBACA,sBACA,qBACA,cACA,YACA,OAAO,cACe;CACtB,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,iBAAiB,aAAa;CAE9B,MAAM,YAAY,aAAa,EAAE,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAAE,CAAC;CAI5E,IAAI;CACJ,IAAI;CAEJ,IAAI,SAAS,SAAS;EACpB,MAAM,WAAW,MAAM,QAAQ,eAAe,SAAS;EAEvD,IAAI,CAAC,UAAU,aAAa,OAAO,CAAC;EAEpC,WAAW,SAAS;EACpB,WAAW,SAAS;EAEpB,IAAI,SAAS,cAAc,YAAY,UAAU;GAC/C,MAAM,EAAE,aAAa,UAAU,MAAM,SAAS,iBAAiB,QAAQ;GACvE,IAAI,CAAC,aAAa;IAChB,UAAU,GAAG,EAAE,GAAG,OAAO;IACzB,OAAO,CAAC;GACV;EACF;CACF;CAEA,IAAI,+BAA+B,8BAA8B,IAAI;EACnE,UACE,kDAAkD,4BAA4B,8CAChF;EACA,8BAA8B;CAChC;CAEA,IAAI,UAAoB,MAAM,GAAG,YAAY,EAC3C,QAAQ,oBACV,CAAC;CAED,IAAI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2B,SAAS,MAAM;CAEjE,IAAI,SAAS,aAAa,eAAe,MAAM;CAE/C,MAAM,YACJ,UACA,OAAO,SAAS;EACd,MAAM,KAAK;EACX,eAAe,UAAU;CAC3B,GACA,+BAA+B,CACjC;CAEA,eAAe,KAAK;CAEpB,MAAM,YAAY,sBAAsB,eAAe,EACrD,mBAAmB,SAAS,QAC9B,CAAC;CAED,KAAK,MAAM,QAAQ,UAAU,MAAM,IAAI,GACrC,UAAU,IAAI;CAGhB,OAAO;AACT"}
|
|
@@ -38,8 +38,10 @@ const reviewFileBlockAware = async (baseFilePath, outputFilePath, locale, baseLo
|
|
|
38
38
|
const baseText = await readFile(baseFilePath, "utf-8");
|
|
39
39
|
const targetText = await readFile(outputFilePath, "utf-8").catch(() => "");
|
|
40
40
|
const basePrompt = readAsset("./prompts/REVIEW_PROMPT.md", "utf-8").replaceAll("{{localeName}}", `${formatLocale(locale, false)}`).replaceAll("{{baseLocaleName}}", `${formatLocale(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
|
|
41
|
-
const
|
|
42
|
-
const
|
|
41
|
+
const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;
|
|
42
|
+
const filePrefix = [colon(filePrefixText, { colSize: 40 }), `→ ${ANSIColors.RESET}`].join("");
|
|
43
|
+
const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;
|
|
44
|
+
const prefix = [colon(prefixText, { colSize: 40 }), `→ ${ANSIColors.RESET}`].join("");
|
|
43
45
|
const { baseBlocks, targetBlocks, plan, segmentsToReview } = buildAlignmentPlan({
|
|
44
46
|
baseText,
|
|
45
47
|
targetText,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewDocBlockAware.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n type PlannedAction,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n *\n * 1. Segments both base and target documents into semantic blocks.\n * 2. Aligns blocks using structure (special chars, numbers) and context.\n * 3. Detects which blocks changed, were added, or deleted.\n * 4. Applies deletions immediately without AI.\n * 5. Sends changed/new blocks to AI in bottom-up order (last block first), so\n * line numbers of earlier blocks are not shifted by edits below them.\n * 6. Rewrites the file after each block so progress is persisted incrementally.\n *\n * @returns The per-action block counts of the alignment plan, so the caller can\n * synthesize what was reused and what had to be edited.\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ReviewReportSummary> => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger({\n log: { ...configuration.log, prefix: '' },\n });\n\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_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 filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { baseBlocks, targetBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n baseText,\n targetText,\n changedLines,\n });\n\n const countActions = (kind: PlannedAction['kind']): number =>\n plan.actions.filter((action: PlannedAction) => action.kind === kind).length;\n\n const reviewSummary: ReviewReportSummary = {\n reuse: countActions('reuse'),\n review: countActions('review'),\n insertNew: countActions('insert_new'),\n delete: countActions('delete'),\n };\n\n const deleteCount = reviewSummary.delete;\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: base=${colorizeNumber(baseBlocks.length)}, target=${colorizeNumber(targetBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(reviewSummary.reuse)}, review=${colorizeNumber(reviewSummary.review)}, new=${colorizeNumber(reviewSummary.insertNew)}, delete=${colorizeNumber(deleteCount)}`\n );\n\n // Map shared across the entire run: each entry overrides the default behavior\n // of mergeReviewedSegments for that action index.\n const reviewedSegmentsMap = new Map<number, string>();\n\n // --- Step 1: apply deletions immediately (no AI needed) ---\n for (const [actionIndex, action] of plan.actions.entries()) {\n if (action.kind === 'delete') {\n reviewedSegmentsMap.set(actionIndex, '');\n }\n }\n\n const writeCurrentState = (): void => {\n const output = mergeReviewedSegments(\n plan,\n targetBlocks,\n reviewedSegmentsMap\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, output);\n };\n\n if (deleteCount > 0) {\n writeCurrentState();\n applicationLogger(\n `${filePrefix}${colorizeNumber(deleteCount)} block(s) deleted without AI.`\n );\n }\n\n if (segmentsToReview.length === 0) {\n if (deleteCount === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n writeCurrentState();\n }\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no AI changes needed).`\n );\n return reviewSummary;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)} (processing bottom-up)`\n );\n\n // --- Step 2: process AI segments in bottom-up order ---\n // Reversing ensures edits near the end of the file don't shift line numbers\n // that matter for blocks higher up, and each intermediate file write is valid.\n const segmentsBottomUp = segmentsToReview\n .map((segment, originalIndex) => ({\n segment,\n displayNumber: originalIndex + 1,\n }))\n .reverse();\n\n for (const { segment, displayNumber } of segmentsBottomUp) {\n const baseBlock = segment.baseBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n` +\n baseBlock.content +\n `///chunksEnd///`;\n\n const getTargetChunkPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n` +\n (segment.targetBlockText ?? '') +\n `///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getTargetChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n ],\n [{ role: 'user', content: baseBlock.content }],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n baseBlock.content\n );\n processedChunk = fixChunkStartEndChars(processedChunk, baseBlock.content);\n\n const isValid = validateTranslation(\n baseBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n\n // Rewrite the file after every block so progress is never lost.\n writeCurrentState();\n }\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n\n return reviewSummary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,uBAAuB,OAClC,cACA,gBACA,QACA,YACA,WACA,eACA,oBACA,cACA,UACA,aACiC;CACjC,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,MAAM,oBAAoB,aAAa,EACrC,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAC1C,CAAC;CAED,MAAM,WAAW,MAAM,SAAS,cAAc,OAAO;CACrD,MAAM,aAAa,MAAM,SAAS,gBAAgB,OAAO,CAAC,CAAC,YAAY,EAAE;CAEzE,MAAM,aAAa,UAAU,8BAA8B,OAAO,CAAC,CAChE,WAAW,kBAAkB,GAAG,aAAa,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AChN;GACF,GACA,CAAC;IAAE,MAAM;IAAQ,SAAS,UAAU;GAAQ,CAAC,GAC7C,WACA,eACA,UACA,QACF;GAEA,kBACE,GAAG,SAAS,eAAe,OAAO,SAAS,EAAE,uBAAuB,eAAe,aAAa,EAAE,MAAM,eAAe,iBAAiB,MAAM,GAChJ;GAEA,IAAI,iBAAiB,cACnB,QAAQ,aACR,UAAU,OACZ;GACA,iBAAiB,sBAAsB,gBAAgB,UAAU,OAAO;GAQxE,IAAI,CANY,oBACd,UAAU,SACV,gBACA,iBAGS,GACT,MAAM,IAAI,MACR,yEACF;GAGF,OAAO;EACT,CAAC,CAAC,CAAC;EAEH,oBAAoB,IAAI,QAAQ,aAAa,mBAAmB;EAGhE,kBAAkB;CACpB;CAEA,kBACE,GAAG,SAAS,KAAK,WAAW,KAAK,EAAE,QAAQ,WAAW,cAAc,EAAE,+BACxE;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"reviewDocBlockAware.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n type PlannedAction,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n *\n * 1. Segments both base and target documents into semantic blocks.\n * 2. Aligns blocks using structure (special chars, numbers) and context.\n * 3. Detects which blocks changed, were added, or deleted.\n * 4. Applies deletions immediately without AI.\n * 5. Sends changed/new blocks to AI in bottom-up order (last block first), so\n * line numbers of earlier blocks are not shifted by edits below them.\n * 6. Rewrites the file after each block so progress is persisted incrementally.\n *\n * @returns The per-action block counts of the alignment plan, so the caller can\n * synthesize what was reused and what had to be edited.\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ReviewReportSummary> => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger({\n log: { ...configuration.log, prefix: '' },\n });\n\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_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 filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { baseBlocks, targetBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n baseText,\n targetText,\n changedLines,\n });\n\n const countActions = (kind: PlannedAction['kind']): number =>\n plan.actions.filter((action: PlannedAction) => action.kind === kind).length;\n\n const reviewSummary: ReviewReportSummary = {\n reuse: countActions('reuse'),\n review: countActions('review'),\n insertNew: countActions('insert_new'),\n delete: countActions('delete'),\n };\n\n const deleteCount = reviewSummary.delete;\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: base=${colorizeNumber(baseBlocks.length)}, target=${colorizeNumber(targetBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(reviewSummary.reuse)}, review=${colorizeNumber(reviewSummary.review)}, new=${colorizeNumber(reviewSummary.insertNew)}, delete=${colorizeNumber(deleteCount)}`\n );\n\n // Map shared across the entire run: each entry overrides the default behavior\n // of mergeReviewedSegments for that action index.\n const reviewedSegmentsMap = new Map<number, string>();\n\n // --- Step 1: apply deletions immediately (no AI needed) ---\n for (const [actionIndex, action] of plan.actions.entries()) {\n if (action.kind === 'delete') {\n reviewedSegmentsMap.set(actionIndex, '');\n }\n }\n\n const writeCurrentState = (): void => {\n const output = mergeReviewedSegments(\n plan,\n targetBlocks,\n reviewedSegmentsMap\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, output);\n };\n\n if (deleteCount > 0) {\n writeCurrentState();\n applicationLogger(\n `${filePrefix}${colorizeNumber(deleteCount)} block(s) deleted without AI.`\n );\n }\n\n if (segmentsToReview.length === 0) {\n if (deleteCount === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n writeCurrentState();\n }\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no AI changes needed).`\n );\n return reviewSummary;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)} (processing bottom-up)`\n );\n\n // --- Step 2: process AI segments in bottom-up order ---\n // Reversing ensures edits near the end of the file don't shift line numbers\n // that matter for blocks higher up, and each intermediate file write is valid.\n const segmentsBottomUp = segmentsToReview\n .map((segment, originalIndex) => ({\n segment,\n displayNumber: originalIndex + 1,\n }))\n .reverse();\n\n for (const { segment, displayNumber } of segmentsBottomUp) {\n const baseBlock = segment.baseBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n` +\n baseBlock.content +\n `///chunksEnd///`;\n\n const getTargetChunkPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n` +\n (segment.targetBlockText ?? '') +\n `///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getTargetChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n ],\n [{ role: 'user', content: baseBlock.content }],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n baseBlock.content\n );\n processedChunk = fixChunkStartEndChars(processedChunk, baseBlock.content);\n\n const isValid = validateTranslation(\n baseBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n\n // Rewrite the file after every block so progress is never lost.\n writeCurrentState();\n }\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n\n return reviewSummary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,uBAAuB,OAClC,cACA,gBACA,QACA,YACA,WACA,eACA,oBACA,cACA,UACA,aACiC;CACjC,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,MAAM,oBAAoB,aAAa,EACrC,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAC1C,CAAC;CAED,MAAM,WAAW,MAAM,SAAS,cAAc,OAAO;CACrD,MAAM,aAAa,MAAM,SAAS,gBAAgB,OAAO,CAAC,CAAC,YAAY,EAAE;CAEzE,MAAM,aAAa,UAAU,8BAA8B,OAAO,CAAC,CAChE,WAAW,kBAAkB,GAAG,aAAa,QAAQ,KAAK,GAAG,CAAC,CAC9D,WAAW,sBAAsB,GAAG,aAAa,YAAY,KAAK,GAAG,CAAC,CACtE,QAAQ,0BAA0B,WAAW,sBAAsB,GAAG,CAAC,CACvE,QAAQ,0BAA0B,sBAAsB,GAAG;CAE9D,MAAM,iBAAiB,GAAG,WAAW,UAAU,GAAG,WAAW,YAAY,IAAI,WAAW,UAAU;CAClG,MAAM,aAAa,CACjB,MAAM,gBAAgB,EAAE,SAAS,GAAG,CAAC,GACrC,KAAK,WAAW,OAClB,CAAC,CAAC,KAAK,EAAE;CACT,MAAM,aAAa,GAAG,WAAW,UAAU,GAAG,WAAW,YAAY,IAAI,WAAW,UAAU,IAAI,aAAa,MAAM,IAAI,WAAW,UAAU;CAC9I,MAAM,SAAS,CACb,MAAM,YAAY,EAAE,SAAS,GAAG,CAAC,GACjC,KAAK,WAAW,OAClB,CAAC,CAAC,KAAK,EAAE;CAGT,MAAM,EAAE,YAAY,cAAc,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ACT"}
|
|
@@ -15,9 +15,11 @@ import { buildReviewReport, formatReviewReport } from "@intlayer/engine/docRevie
|
|
|
15
15
|
* @returns The structured review report.
|
|
16
16
|
*/
|
|
17
17
|
const buildFileReviewReport = async (baseFilePath, outputFilePath, changedLines) => {
|
|
18
|
+
const baseText = await readFile(baseFilePath, "utf-8");
|
|
19
|
+
const targetText = existsSync(outputFilePath) ? await readFile(outputFilePath, "utf-8").catch(() => "") : "";
|
|
18
20
|
return buildReviewReport({
|
|
19
|
-
baseText
|
|
20
|
-
targetText
|
|
21
|
+
baseText,
|
|
22
|
+
targetText,
|
|
21
23
|
changedLines
|
|
22
24
|
});
|
|
23
25
|
};
|
|
@@ -33,8 +35,9 @@ const buildFileReviewReport = async (baseFilePath, outputFilePath, changedLines)
|
|
|
33
35
|
* @param configOptions - Optional Intlayer configuration overrides.
|
|
34
36
|
*/
|
|
35
37
|
const logReviewFileBlocks = (report, baseFilePath, locale, baseLocale, configOptions) => {
|
|
38
|
+
const configuration = getConfiguration(configOptions);
|
|
36
39
|
const appLogger = getAppLogger({ log: {
|
|
37
|
-
...
|
|
40
|
+
...configuration.log,
|
|
38
41
|
prefix: ""
|
|
39
42
|
} });
|
|
40
43
|
const formatted = formatReviewReport(report, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewDocLog.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDocLog.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n buildReviewReport,\n formatReviewReport,\n type ReviewReport,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\n\n/**\n * Compare a base document with its translation without calling any AI.\n *\n * @param baseFilePath - Absolute path of the base (source) document.\n * @param outputFilePath - Absolute path of the target (translated) document.\n * @param changedLines - 1-based base line numbers that changed (from git), if any.\n * @returns The structured review report.\n */\nexport const buildFileReviewReport = async (\n baseFilePath: string,\n outputFilePath: string,\n changedLines?: number[]\n): Promise<ReviewReport> => {\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = existsSync(outputFilePath)\n ? await readFile(outputFilePath, 'utf-8').catch(() => '')\n : '';\n\n return buildReviewReport({ baseText, targetText, changedLines });\n};\n\n/**\n * Log the blocks that need attention (with their line ranges and content) for a\n * single file/locale pair, so another agent or a human can generate the missing\n * translations.\n *\n * @param report - The report built by {@link buildFileReviewReport}.\n * @param baseFilePath - Absolute path of the base (source) document.\n * @param locale - The target locale being reviewed.\n * @param baseLocale - The base locale used as reference.\n * @param configOptions - Optional Intlayer configuration overrides.\n */\nexport const logReviewFileBlocks = (\n report: ReviewReport,\n baseFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n configOptions?: GetConfigurationOptions\n): void => {\n const configuration = getConfiguration(configOptions);\n const appLogger = getAppLogger({ log: { ...configuration.log, prefix: '' } });\n\n const formatted = formatReviewReport(report, {\n baseLabel: formatLocale(baseLocale),\n targetLabel: formatLocale(locale),\n });\n\n appLogger(`${formatPath(baseFilePath)} → ${formatLocale(locale)}`);\n for (const line of formatted.split('\\n')) {\n appLogger(line);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAa,wBAAwB,OACnC,cACA,gBACA,iBAC0B;
|
|
1
|
+
{"version":3,"file":"reviewDocLog.mjs","names":[],"sources":["../../../src/reviewDoc/reviewDocLog.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n buildReviewReport,\n formatReviewReport,\n type ReviewReport,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\n\n/**\n * Compare a base document with its translation without calling any AI.\n *\n * @param baseFilePath - Absolute path of the base (source) document.\n * @param outputFilePath - Absolute path of the target (translated) document.\n * @param changedLines - 1-based base line numbers that changed (from git), if any.\n * @returns The structured review report.\n */\nexport const buildFileReviewReport = async (\n baseFilePath: string,\n outputFilePath: string,\n changedLines?: number[]\n): Promise<ReviewReport> => {\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = existsSync(outputFilePath)\n ? await readFile(outputFilePath, 'utf-8').catch(() => '')\n : '';\n\n return buildReviewReport({ baseText, targetText, changedLines });\n};\n\n/**\n * Log the blocks that need attention (with their line ranges and content) for a\n * single file/locale pair, so another agent or a human can generate the missing\n * translations.\n *\n * @param report - The report built by {@link buildFileReviewReport}.\n * @param baseFilePath - Absolute path of the base (source) document.\n * @param locale - The target locale being reviewed.\n * @param baseLocale - The base locale used as reference.\n * @param configOptions - Optional Intlayer configuration overrides.\n */\nexport const logReviewFileBlocks = (\n report: ReviewReport,\n baseFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n configOptions?: GetConfigurationOptions\n): void => {\n const configuration = getConfiguration(configOptions);\n const appLogger = getAppLogger({ log: { ...configuration.log, prefix: '' } });\n\n const formatted = formatReviewReport(report, {\n baseLabel: formatLocale(baseLocale),\n targetLabel: formatLocale(locale),\n });\n\n appLogger(`${formatPath(baseFilePath)} → ${formatLocale(locale)}`);\n for (const line of formatted.split('\\n')) {\n appLogger(line);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAa,wBAAwB,OACnC,cACA,gBACA,iBAC0B;CAC1B,MAAM,WAAW,MAAM,SAAS,cAAc,OAAO;CACrD,MAAM,aAAa,WAAW,cAAc,IACxC,MAAM,SAAS,gBAAgB,OAAO,CAAC,CAAC,YAAY,EAAE,IACtD;CAEJ,OAAO,kBAAkB;EAAE;EAAU;EAAY;CAAa,CAAC;AACjE;;;;;;;;;;;;AAaA,MAAa,uBACX,QACA,cACA,QACA,YACA,kBACS;CACT,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,MAAM,YAAY,aAAa,EAAE,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAAE,CAAC;CAE5E,MAAM,YAAY,mBAAmB,QAAQ;EAC3C,WAAW,aAAa,UAAU;EAClC,aAAa,aAAa,MAAM;CAClC,CAAC;CAED,UAAU,GAAG,WAAW,YAAY,EAAE,KAAK,aAAa,MAAM,GAAG;CACjE,KAAK,MAAM,QAAQ,UAAU,MAAM,IAAI,GACrC,UAAU,IAAI;AAElB"}
|
package/dist/esm/scan.mjs
CHANGED
|
@@ -42,7 +42,8 @@ const scoreColor = (score) => {
|
|
|
42
42
|
* ```
|
|
43
43
|
*/
|
|
44
44
|
const scan = async (url, options = {}) => {
|
|
45
|
-
const
|
|
45
|
+
const configuration = getConfiguration(options.configOptions);
|
|
46
|
+
const appLogger = getAppLogger(configuration);
|
|
46
47
|
const result = await scanWebsite(url, { deep: options.deep });
|
|
47
48
|
if (options.json) {
|
|
48
49
|
appLogger(JSON.stringify(result, null, 2));
|
package/dist/esm/scan.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scan.mjs","names":[],"sources":["../../src/scan.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { formatSize, type ScanEvent, scanWebsite } from '@intlayer/engine/scan';\nimport type { ConfigurationOptions } from './cli';\n\n/** Options accepted by the {@link scan} command. */\nexport type ScanCommandOptions = {\n /** Disable the deeper puppeteer-based render scan. */\n deep?: boolean;\n /** Output the raw {@link ScanResult} as JSON instead of formatted text. */\n json?: boolean;\n configOptions?: ConfigurationOptions;\n};\n\n/** Human-readable labels for each scorable check type. */\nconst checkLabels: Record<string, string> = {\n robots_robotsPresent: 'robots.txt present',\n robots_noLocalizedUrlsForgotten: 'robots.txt keeps locale paths crawlable',\n sitemap_sitemapPresent: 'sitemap.xml present',\n sitemap_noLocalizedUrlsForgotten: 'sitemap lists every locale',\n sitemap_hasAlternates: 'sitemap has alternate links',\n sitemap_hasXDefault: 'sitemap has x-default',\n url_htmlLang: 'html lang attribute',\n url_htmlDir: 'html dir attribute',\n url_hasCanonical: 'canonical link',\n url_hreflang: 'hreflang tags',\n url_hasLocalizedLinks: 'localized internal links',\n url_hasXDefault: 'x-default hreflang',\n url_allAnchorsLocalized: 'all internal links localized',\n url_currentLocale: 'current locale detected',\n url_unusedBundleContent: 'unused bundle locale content',\n};\n\nconst statusIcon = (status: ScanEvent['status']): string => {\n if (status === 'success') return colorize('✓', ANSIColors.GREEN);\n if (status === 'warning') return colorize('⚠', ANSIColors.YELLOW);\n return colorize('✗', ANSIColors.RED);\n};\n\nconst scoreColor = (score: number) => {\n if (score >= 80) return ANSIColors.GREEN;\n if (score >= 50) return ANSIColors.YELLOW;\n return ANSIColors.RED;\n};\n\n/**\n * Scan a website for i18n/SEO health and bundle weight, printing a formatted\n * report (or JSON with `--json`).\n *\n * @example\n * ```sh\n * npx intlayer scan https://intlayer.org\n * ```\n */\nexport const scan = async (\n url: string,\n options: ScanCommandOptions = {}\n): Promise<void> => {\n const configuration = getConfiguration(options.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const result = await scanWebsite(url, { deep: options.deep });\n\n if (options.json) {\n appLogger(JSON.stringify(result, null, 2));\n return;\n }\n\n appLogger(\n `\\n🔍 Scanned ${colorize(result.url, ANSIColors.GREY_LIGHT)} ${colorize(\n `(${result.mode} mode)`,\n ANSIColors.GREY\n )}\\n`\n );\n\n appLogger(\n `Score: ${colorize(`${result.score}/100`, scoreColor(result.score))}`\n );\n appLogger(\n `Page size: ${colorize(formatSize(result.totalPageSize), ANSIColors.BLUE)} ${colorize(\n `(HTML ${formatSize(result.htmlSize)})`,\n ANSIColors.GREY\n )}`\n );\n if (result.locales.length > 0) {\n appLogger(\n `Locales: ${colorize(result.locales.join(', '), ANSIColors.GREEN)}`\n );\n }\n\n appLogger('\\nChecks:');\n for (const event of result.events) {\n const type = event.type.split('\\\\')[0];\n\n if (!type) continue;\n\n const label = checkLabels[type] ?? type;\n appLogger(` ${statusIcon(event.status)} ${label}`);\n }\n\n if (result.bundle && result.bundle.totalLocaleSize > 0) {\n const { bundle } = result;\n appLogger('\\nBundle locale weight:');\n appLogger(\n ` Translations shipped: ${colorize(formatSize(bundle.totalLocaleSize), ANSIColors.BLUE)}`\n );\n appLogger(\n ` Unused (other locales): ${colorize(\n `${formatSize(bundle.totalUnusedLocaleSize)} (${bundle.unusedPercentOfLocale}%)`,\n bundle.unusedPercentOfLocale > 30\n ? ANSIColors.RED\n : bundle.unusedPercentOfLocale > 0\n ? ANSIColors.YELLOW\n : ANSIColors.GREEN\n )}`\n );\n }\n};\n"],"mappings":";;;;;;;AAgBA,MAAM,cAAsC;CAC1C,sBAAsB;CACtB,iCAAiC;CACjC,wBAAwB;CACxB,kCAAkC;CAClC,uBAAuB;CACvB,qBAAqB;CACrB,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,uBAAuB;CACvB,iBAAiB;CACjB,yBAAyB;CACzB,mBAAmB;CACnB,yBAAyB;AAC3B;AAEA,MAAM,cAAc,WAAwC;CAC1D,IAAI,WAAW,WAAW,OAAO,SAAS,KAAK,WAAW,KAAK;CAC/D,IAAI,WAAW,WAAW,OAAO,SAAS,KAAK,WAAW,MAAM;CAChE,OAAO,SAAS,KAAK,WAAW,GAAG;AACrC;AAEA,MAAM,cAAc,UAAkB;CACpC,IAAI,SAAS,IAAI,OAAO,WAAW;CACnC,IAAI,SAAS,IAAI,OAAO,WAAW;CACnC,OAAO,WAAW;AACpB;;;;;;;;;;AAWA,MAAa,OAAO,OAClB,KACA,UAA8B,CAAC,MACb;
|
|
1
|
+
{"version":3,"file":"scan.mjs","names":[],"sources":["../../src/scan.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { formatSize, type ScanEvent, scanWebsite } from '@intlayer/engine/scan';\nimport type { ConfigurationOptions } from './cli';\n\n/** Options accepted by the {@link scan} command. */\nexport type ScanCommandOptions = {\n /** Disable the deeper puppeteer-based render scan. */\n deep?: boolean;\n /** Output the raw {@link ScanResult} as JSON instead of formatted text. */\n json?: boolean;\n configOptions?: ConfigurationOptions;\n};\n\n/** Human-readable labels for each scorable check type. */\nconst checkLabels: Record<string, string> = {\n robots_robotsPresent: 'robots.txt present',\n robots_noLocalizedUrlsForgotten: 'robots.txt keeps locale paths crawlable',\n sitemap_sitemapPresent: 'sitemap.xml present',\n sitemap_noLocalizedUrlsForgotten: 'sitemap lists every locale',\n sitemap_hasAlternates: 'sitemap has alternate links',\n sitemap_hasXDefault: 'sitemap has x-default',\n url_htmlLang: 'html lang attribute',\n url_htmlDir: 'html dir attribute',\n url_hasCanonical: 'canonical link',\n url_hreflang: 'hreflang tags',\n url_hasLocalizedLinks: 'localized internal links',\n url_hasXDefault: 'x-default hreflang',\n url_allAnchorsLocalized: 'all internal links localized',\n url_currentLocale: 'current locale detected',\n url_unusedBundleContent: 'unused bundle locale content',\n};\n\nconst statusIcon = (status: ScanEvent['status']): string => {\n if (status === 'success') return colorize('✓', ANSIColors.GREEN);\n if (status === 'warning') return colorize('⚠', ANSIColors.YELLOW);\n return colorize('✗', ANSIColors.RED);\n};\n\nconst scoreColor = (score: number) => {\n if (score >= 80) return ANSIColors.GREEN;\n if (score >= 50) return ANSIColors.YELLOW;\n return ANSIColors.RED;\n};\n\n/**\n * Scan a website for i18n/SEO health and bundle weight, printing a formatted\n * report (or JSON with `--json`).\n *\n * @example\n * ```sh\n * npx intlayer scan https://intlayer.org\n * ```\n */\nexport const scan = async (\n url: string,\n options: ScanCommandOptions = {}\n): Promise<void> => {\n const configuration = getConfiguration(options.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const result = await scanWebsite(url, { deep: options.deep });\n\n if (options.json) {\n appLogger(JSON.stringify(result, null, 2));\n return;\n }\n\n appLogger(\n `\\n🔍 Scanned ${colorize(result.url, ANSIColors.GREY_LIGHT)} ${colorize(\n `(${result.mode} mode)`,\n ANSIColors.GREY\n )}\\n`\n );\n\n appLogger(\n `Score: ${colorize(`${result.score}/100`, scoreColor(result.score))}`\n );\n appLogger(\n `Page size: ${colorize(formatSize(result.totalPageSize), ANSIColors.BLUE)} ${colorize(\n `(HTML ${formatSize(result.htmlSize)})`,\n ANSIColors.GREY\n )}`\n );\n if (result.locales.length > 0) {\n appLogger(\n `Locales: ${colorize(result.locales.join(', '), ANSIColors.GREEN)}`\n );\n }\n\n appLogger('\\nChecks:');\n for (const event of result.events) {\n const type = event.type.split('\\\\')[0];\n\n if (!type) continue;\n\n const label = checkLabels[type] ?? type;\n appLogger(` ${statusIcon(event.status)} ${label}`);\n }\n\n if (result.bundle && result.bundle.totalLocaleSize > 0) {\n const { bundle } = result;\n appLogger('\\nBundle locale weight:');\n appLogger(\n ` Translations shipped: ${colorize(formatSize(bundle.totalLocaleSize), ANSIColors.BLUE)}`\n );\n appLogger(\n ` Unused (other locales): ${colorize(\n `${formatSize(bundle.totalUnusedLocaleSize)} (${bundle.unusedPercentOfLocale}%)`,\n bundle.unusedPercentOfLocale > 30\n ? ANSIColors.RED\n : bundle.unusedPercentOfLocale > 0\n ? ANSIColors.YELLOW\n : ANSIColors.GREEN\n )}`\n );\n }\n};\n"],"mappings":";;;;;;;AAgBA,MAAM,cAAsC;CAC1C,sBAAsB;CACtB,iCAAiC;CACjC,wBAAwB;CACxB,kCAAkC;CAClC,uBAAuB;CACvB,qBAAqB;CACrB,cAAc;CACd,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,uBAAuB;CACvB,iBAAiB;CACjB,yBAAyB;CACzB,mBAAmB;CACnB,yBAAyB;AAC3B;AAEA,MAAM,cAAc,WAAwC;CAC1D,IAAI,WAAW,WAAW,OAAO,SAAS,KAAK,WAAW,KAAK;CAC/D,IAAI,WAAW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B;EACnC,UACE,2BAA2B,SAAS,WAAW,OAAO,eAAe,GAAG,WAAW,IAAI,GACzF;EACA,UACE,6BAA6B,SAC3B,GAAG,WAAW,OAAO,qBAAqB,EAAE,IAAI,OAAO,sBAAsB,KAC7E,OAAO,wBAAwB,KAC3B,WAAW,MACX,OAAO,wBAAwB,IAC7B,WAAW,SACX,WAAW,KACnB,GACF;CACF;AACF"}
|
|
@@ -41,7 +41,7 @@ const translateDoc = async ({ docPattern, locales, excludedGlobPattern, baseLoca
|
|
|
41
41
|
maxErrors: 5,
|
|
42
42
|
shouldStop: false
|
|
43
43
|
};
|
|
44
|
-
|
|
44
|
+
const allTasks = docList.flatMap((docPath) => locales.map((locale) => async () => {
|
|
45
45
|
if (errorState.shouldStop) return;
|
|
46
46
|
const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);
|
|
47
47
|
const outputFilePath = getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
|
|
@@ -72,7 +72,8 @@ const translateDoc = async ({ docPattern, locales, excludedGlobPattern, baseLoca
|
|
|
72
72
|
flushStrategy,
|
|
73
73
|
limit: globalChunkLimiter
|
|
74
74
|
});
|
|
75
|
-
}))
|
|
75
|
+
}));
|
|
76
|
+
await parallelize(allTasks, (task) => task(), 50);
|
|
76
77
|
const batchDuration = ((performance.now() - batchStartTime) / 1e3).toFixed(2);
|
|
77
78
|
if (errorState.count > 0) appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);
|
|
78
79
|
else appLogger(`${colorize("✔", ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`);
|
|
@@ -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 * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { listGitFiles, logConfigDetails } from '@intlayer/engine/cli';\nimport { parallelize, pLimit } from '@intlayer/engine/utils';\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\n const { aiClient, aiConfig, isCustomAI } = aiResult;\n if (isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return;\n }\n }\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 // 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 // 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":";;;;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAAO,EACjC,YACA,SACA,qBACA,YACA,WACA,8BAA8B,IAC9B,eACA,oBACA,sBACA,qBACA,cACA,YACA,gBAAgB,oBACS;CACzB,MAAM,gBAAgB,iBAAiB,aAAa;CACpD,iBAAiB,aAAa;CAE9B,MAAM,YAAY,aAAa,aAAa;CAK5C,MAAM,sBAAsB;CAC5B,MAAM,qBAAqB,OAAO,mBAAmB;CAErD,IAAI,UAAoB,MAAM,GAAG,YAAY,EAC3C,QAAQ,oBACV,CAAC;CAED,MAAM,WAAW,MAAM,QAAQ,eAAe,SAAS;CACvD,IAAI,CAAC,UAAU,aAAa;CAE5B,MAAM,EAAE,UAAU,UAAU,eAAe;CAC3C,IAAI,cAAc,YAAY,UAAU;EACtC,MAAM,EAAE,aAAa,UAAU,MAAM,SAAS,iBAAiB,QAAQ;EACvE,IAAI,CAAC,aAAa;GAChB,UAAU,GAAG,EAAE,GAAG,OAAO;GACzB;EACF;CACF;CAEA,IAAI,YAAY;EACd,MAAM,kBAAkB,MAAM,aAAa,UAAU;EACrD,IAAI,iBACF,UAAU,QAAQ,QAAQ,SACxB,gBAAgB,MAAM,YAAY,KAAK,QAAQ,IAAI,GAAG,IAAI,MAAM,OAAO,CACzE;CAEJ;CAEA,MAAM,iBAAiB,YAAY,IAAI;CAEvC,UACE,eAAe,eAAe,QAAQ,MAAM,EAAE,YAAY,eAAe,QAAQ,MAAM,EAAE,kCAChE,eAAe,mBAAmB,EAAE,qBAC/D;CAEA,MAAM,aAAyB;EAC7B,OAAO;EACP,WAAW;EACX,YAAY;CACd;
|
|
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 * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { listGitFiles, logConfigDetails } from '@intlayer/engine/cli';\nimport { parallelize, pLimit } from '@intlayer/engine/utils';\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\n const { aiClient, aiConfig, isCustomAI } = aiResult;\n if (isCustomAI && aiClient && aiConfig) {\n const { hasAIAccess, error } = await aiClient.checkAISDKAccess(aiConfig);\n if (!hasAIAccess) {\n appLogger(`${x} ${error}`);\n return;\n }\n }\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 // 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 // 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":";;;;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAAO,EACjC,YACA,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AAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;GACtD,cAAc,gBAAgB,EAAE;EAClC;EAEA,MAAM,uBAAuB,uBAAuB,gBAAgB;GAClE;GACA;EACF,CAAC;EAED,IAAI,qBAAqB,WAAW;GAClC,UAAU,qBAAqB,OAAO;GACtC;EACF;EAGA,MAAM,cAAc;GAClB,cAAc;GACd;GACQ;GACR;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;EACT,CAAC;CACH,CAAC,CACH;CAQA,MAAM,YAAY,WAAW,SAAS,KAAK,GAAG,EAAe;CAG7D,MAAM,kBADe,YAAY,IACE,IAAI,kBAAkB,IAAI,CAAE,QAAQ,CAAC;CAExE,IAAI,WAAW,QAAQ,GACrB,UAAU,iBAAiB,WAAW,MAAM,aAAa,cAAc,GAAG;MAE1E,UACE,GAAG,SAAS,KAAK,WAAW,KAAK,EAAE,mCAAmC,eAAe,aAAa,EAAE,GACtG;AAEJ"}
|
|
@@ -17,10 +17,13 @@ const translateFile = async ({ baseFilePath, outputFilePath, locale, baseLocale,
|
|
|
17
17
|
const appLogger = getAppLogger(configuration, { config: { prefix: "" } });
|
|
18
18
|
const fileStartTime = performance.now();
|
|
19
19
|
try {
|
|
20
|
-
const
|
|
20
|
+
const fileContent = await readFile(baseFilePath, "utf-8");
|
|
21
|
+
const chunks = chunkText(fileContent);
|
|
21
22
|
const totalChunks = chunks.length;
|
|
22
|
-
const
|
|
23
|
-
const
|
|
23
|
+
const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;
|
|
24
|
+
const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;
|
|
25
|
+
const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;
|
|
26
|
+
const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;
|
|
24
27
|
appLogger(`${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`);
|
|
25
28
|
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 ?? "-");
|
|
26
29
|
const translatedParts = new Array(totalChunks).fill("");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\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 { formatLocale, formatPath } from '@intlayer/engine/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 [\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 await mkdir(dirname(outputFilePath), { recursive: true });\n await writeFile(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 await mkdir(dirname(outputFilePath), { recursive: true });\n await writeFile(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":";;;;;;;;;;;;;;AAmBA,MAAa,gBAAgB,OAAO,EAClC,cACA,gBACA,QACA,YACA,eACA,YACA,WACA,oBACA,UACA,UACA,gBAAgB,eAChB,gBACA,YACkD;CAClD,IAAI,WAAW,YAAY,OAAO;CAElC,MAAM,YAAY,aAAa,eAAe,EAAE,QAAQ,EAAE,QAAQ,GAAG,EAAE,CAAC;CACxE,MAAM,gBAAgB,YAAY,IAAI;CAEtC,IAAI;EAEF,MAAM,SAAS,UAAU,MADC,SAAS,cAAc,OAAO,CACpB;EACpC,MAAM,cAAc,OAAO;EAG3B,MAAM,aAAa,GAAG,MAAM,GADF,WAAW,UAAU,GAAG,WAAW,YAAY,IAAI,WAAW,UAAU,KACtD,EAAE,SAAS,GAAG,CAAC,IAAI,WAAW;EAE1E,MAAM,SAAS,GAAG,MAAM,GADF,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AAS,kBAAkB,eAAe;GAC9D,MAAM,MAAM,QAAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;GACxD,MAAM,UAAU,gBAAgB,WAAW;EAC7C;EAGA,MAAM,kBADc,YAAY,IACE,IAAI,iBAAiB,IAAI,CAAE,QAAQ,CAAC;EACtE,MAAM,eAAe,SAAS,cAAc,OAAO,SAAS,cAAc;EAE1E,UACE,GAAG,SAAS,KAAK,WAAW,KAAK,EAAE,QAAQ,WAAW,YAAY,EAAE,gBAAgB,eAAe,aAAa,EAAE,GACpH;EAEA,OAAO;CACT,SAAS,OAAY;EACnB,WAAW;EACX,MAAM,eAAe,OAAO,WAAW,KAAK,UAAU,KAAK;EAC3D,UAAU,GAAG,SAAS,KAAK,WAAW,GAAG,EAAE,UAAU,cAAc;EACnE,IAAI,WAAW,SAAS,WAAW,WAAW,WAAW,aAAa;EACtE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"translateFile.mjs","names":[],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\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 { formatLocale, formatPath } from '@intlayer/engine/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 [\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 await mkdir(dirname(outputFilePath), { recursive: true });\n await writeFile(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 await mkdir(dirname(outputFilePath), { recursive: true });\n await writeFile(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":";;;;;;;;;;;;;;AAmBA,MAAa,gBAAgB,OAAO,EAClC,cACA,gBACA,QACA,YACA,eACA,YACA,WACA,oBACA,UACA,UACA,gBAAgB,eAChB,gBACA,YACkD;CAClD,IAAI,WAAW,YAAY,OAAO;CAElC,MAAM,YAAY,aAAa,eAAe,EAAE,QAAQ,EAAE,QAAQ,GAAG,EAAE,CAAC;CACxE,MAAM,gBAAgB,YAAY,IAAI;CAEtC,IAAI;EAC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AAK,CAAC;KACxD,MAAM,UAAU,gBAAgB,cAAc;IAChD;;GAGF,YACE,CACE,GAAG,eAAe,MAAM,EAAE,gBAC1B,GAAG,WAAW,UAAU,KAAK,eAAe,aAAa,EAAE,IAAI,WAAW,OAC5E,CAAC,CAAC,KAAK,EAAE,CACX;EACF,CAAC,CACH;EAGA,MAAM,QAAQ,IAAI,KAAK;EAGvB,MAAM,cAAc,gBAAgB,KAAK,EAAE;EAC3C,IAAI,kBAAkB,SAAS,kBAAkB,eAAe;GAC9D,MAAM,MAAM,QAAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;GACxD,MAAM,UAAU,gBAAgB,WAAW;EAC7C;EAGA,MAAM,kBADc,YAAY,IACE,IAAI,iBAAiB,IAAI,CAAE,QAAQ,CAAC;EACtE,MAAM,eAAe,SAAS,cAAc,OAAO,SAAS,cAAc;EAE1E,UACE,GAAG,SAAS,KAAK,WAAW,KAAK,EAAE,QAAQ,WAAW,YAAY,EAAE,gBAAgB,eAAe,aAAa,EAAE,GACpH;EAEA,OAAO;CACT,SAAS,OAAY;EACnB,WAAW;EACX,MAAM,eAAe,OAAO,WAAW,KAAK,UAAU,KAAK;EAC3D,UAAU,GAAG,SAAS,KAAK,WAAW,GAAG,EAAE,UAAU,cAAc;EACnE,IAAI,WAAW,SAAS,WAAW,WAAW,WAAW,aAAa;EACtE,OAAO;CACT;AACF"}
|
|
@@ -8,7 +8,7 @@ import { formatTimeDiff } from "./formatTimeDiff.mjs";
|
|
|
8
8
|
* 50 years expressed in milliseconds is far greater than any reasonable
|
|
9
9
|
* "relative" duration we expect the helper to receive (e.g. a couple of years).
|
|
10
10
|
*/
|
|
11
|
-
const TIMESTAMP_THRESHOLD_MS =
|
|
11
|
+
const TIMESTAMP_THRESHOLD_MS = 15768e8;
|
|
12
12
|
/**
|
|
13
13
|
* Normalises the input date representation into a pair:
|
|
14
14
|
* 1. `relativeTime` – a Date instance whose epoch-time equals the duration
|
|
@@ -65,9 +65,10 @@ const checkFileModifiedRange = (filePath, options) => {
|
|
|
65
65
|
else if (maxDate) shouldSkip = fileLastUpdateTime >= maxDate;
|
|
66
66
|
if (shouldSkip) {
|
|
67
67
|
const referenceDate = minDate && maxDate ? new Date(Math.abs(maxDate.getTime() - minDate.getTime())) : minDate ?? maxDate;
|
|
68
|
+
const relativeTime = new Date(now.getTime() - referenceDate.getTime());
|
|
68
69
|
return {
|
|
69
70
|
isSkipped: true,
|
|
70
|
-
message: `Skipping file because it has been modified within the last ${formatTimeDiff(
|
|
71
|
+
message: `Skipping file because it has been modified within the last ${formatTimeDiff(relativeTime)} - ${filePath}`
|
|
71
72
|
};
|
|
72
73
|
}
|
|
73
74
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkFileModifiedRange.mjs","names":[],"sources":["../../../src/utils/checkFileModifiedRange.ts"],"sourcesContent":["import { checkLastUpdateTime } from './checkLastUpdateTime';\nimport { formatTimeDiff } from './formatTimeDiff';\n\ntype GetTimeRangeResult = {\n relativeTime: Date;\n absoluteTime: Date;\n};\n\n/**\n * Threshold that helps us differentiate between a numeric *timestamp* (ms from epoch)\n * and a numeric *duration* (ms ago).\n * 50 years expressed in milliseconds is far greater than any reasonable\n * \"relative\" duration we expect the helper to receive (e.g. a couple of years).\n */\nconst TIMESTAMP_THRESHOLD_MS = 50 * 365 * 24 * 60 * 60 * 1000; // 50 years\n\n/**\n * Normalises the input date representation into a pair:\n * 1. `relativeTime` – a Date instance whose epoch-time equals the duration\n * between `now` and the absolute date.\n * 2. `absoluteTime` – the concrete point in time represented as a Date.\n *\n * Rules for interpreting the input:\n * • Date => treated as an absolute time.\n * • string => parsed via the Date constructor => absolute time.\n * • number:\n * – if the value is larger than the TIMESTAMP_THRESHOLD_MS we assume it\n * is a unix timestamp (absolute time).\n * – otherwise we treat it as a *relative* duration expressed in\n * milliseconds.\n */\nconst normaliseInputDate = (\n date: Date | number | string,\n now: Date = new Date()\n): GetTimeRangeResult => {\n // Case 1: Already a Date instance\n if (date instanceof Date) {\n return {\n absoluteTime: date,\n relativeTime: new Date(now.getTime() - date.getTime()),\n };\n }\n\n // Case 2: Numeric value – decide between timestamp vs relative ms.\n if (typeof date === 'number') {\n if (date > TIMESTAMP_THRESHOLD_MS) {\n // Treat as *unix timestamp* (absolute)\n const absoluteTime = new Date(date);\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n // Treat as a *relative* duration (milliseconds in the past)\n const relativeMs = date;\n return {\n // Relative duration expressed as a Date object starting at the epoch\n relativeTime: new Date(relativeMs),\n // The concrete date obtained by subtracting the duration from *now*\n absoluteTime: new Date(now.getTime() - relativeMs),\n };\n }\n\n // Case 3: String representation – let Date parse it.\n if (typeof date === 'string') {\n const absoluteTime = new Date(date);\n if (Number.isNaN(absoluteTime.getTime())) {\n throw new Error(`Invalid date string provided: ${date}`);\n }\n\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n throw new Error(`Unsupported date format: ${date}`);\n};\n\ntype CheckFileModifiedRangeResult = {\n isSkipped: boolean;\n message: string;\n};\n\ntype CheckFileModifiedRangeOptions = {\n skipIfModifiedBefore?: Date | number | string;\n skipIfModifiedAfter?: Date | number | string;\n};\n\nexport const checkFileModifiedRange = (\n filePath: string,\n options: CheckFileModifiedRangeOptions\n): CheckFileModifiedRangeResult => {\n const fileLastUpdateTime = checkLastUpdateTime(filePath);\n const { skipIfModifiedBefore, skipIfModifiedAfter } = options;\n\n // Normalise the provided thresholds to concrete dates.\n const now = new Date();\n const minDate = skipIfModifiedBefore\n ? normaliseInputDate(skipIfModifiedBefore, now).absoluteTime\n : undefined;\n const maxDate = skipIfModifiedAfter\n ? normaliseInputDate(skipIfModifiedAfter, now).absoluteTime\n : undefined;\n\n // Determine if the file should be skipped.\n let shouldSkip = false;\n\n if (minDate instanceof Date && maxDate instanceof Date) {\n // Skip when the modification time falls *within* the range [minDate, maxDate]\n shouldSkip = fileLastUpdateTime >= minDate && fileLastUpdateTime <= maxDate;\n } else if (minDate instanceof Date) {\n // Only lower bound – skip when the file was modified *after* minDate\n shouldSkip = fileLastUpdateTime >= minDate;\n } else if (maxDate) {\n // Only upper bound – skip when the file was modified *after* maxDate\n shouldSkip = fileLastUpdateTime >= maxDate;\n }\n\n if (shouldSkip) {\n // For the sake of the message we compute the relative time to *now* using\n // whichever bound was responsible for the skip logic.\n const referenceDate = (\n minDate && maxDate\n ? // When both bounds are present, the *range* caused the skip so we use\n // the distance between the two bounds as the relative duration.\n new Date(Math.abs(maxDate.getTime() - minDate.getTime()))\n : (minDate ?? maxDate)\n )!;\n\n const relativeTime = new Date(now.getTime() - referenceDate.getTime());\n\n return {\n isSkipped: true,\n message: `Skipping file because it has been modified within the last ${formatTimeDiff(relativeTime)} - ${filePath}`,\n };\n }\n\n return {\n isSkipped: false,\n message: `File ${filePath} can be processed - ${filePath}`,\n };\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAM,yBAAyB
|
|
1
|
+
{"version":3,"file":"checkFileModifiedRange.mjs","names":[],"sources":["../../../src/utils/checkFileModifiedRange.ts"],"sourcesContent":["import { checkLastUpdateTime } from './checkLastUpdateTime';\nimport { formatTimeDiff } from './formatTimeDiff';\n\ntype GetTimeRangeResult = {\n relativeTime: Date;\n absoluteTime: Date;\n};\n\n/**\n * Threshold that helps us differentiate between a numeric *timestamp* (ms from epoch)\n * and a numeric *duration* (ms ago).\n * 50 years expressed in milliseconds is far greater than any reasonable\n * \"relative\" duration we expect the helper to receive (e.g. a couple of years).\n */\nconst TIMESTAMP_THRESHOLD_MS = 50 * 365 * 24 * 60 * 60 * 1000; // 50 years\n\n/**\n * Normalises the input date representation into a pair:\n * 1. `relativeTime` – a Date instance whose epoch-time equals the duration\n * between `now` and the absolute date.\n * 2. `absoluteTime` – the concrete point in time represented as a Date.\n *\n * Rules for interpreting the input:\n * • Date => treated as an absolute time.\n * • string => parsed via the Date constructor => absolute time.\n * • number:\n * – if the value is larger than the TIMESTAMP_THRESHOLD_MS we assume it\n * is a unix timestamp (absolute time).\n * – otherwise we treat it as a *relative* duration expressed in\n * milliseconds.\n */\nconst normaliseInputDate = (\n date: Date | number | string,\n now: Date = new Date()\n): GetTimeRangeResult => {\n // Case 1: Already a Date instance\n if (date instanceof Date) {\n return {\n absoluteTime: date,\n relativeTime: new Date(now.getTime() - date.getTime()),\n };\n }\n\n // Case 2: Numeric value – decide between timestamp vs relative ms.\n if (typeof date === 'number') {\n if (date > TIMESTAMP_THRESHOLD_MS) {\n // Treat as *unix timestamp* (absolute)\n const absoluteTime = new Date(date);\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n // Treat as a *relative* duration (milliseconds in the past)\n const relativeMs = date;\n return {\n // Relative duration expressed as a Date object starting at the epoch\n relativeTime: new Date(relativeMs),\n // The concrete date obtained by subtracting the duration from *now*\n absoluteTime: new Date(now.getTime() - relativeMs),\n };\n }\n\n // Case 3: String representation – let Date parse it.\n if (typeof date === 'string') {\n const absoluteTime = new Date(date);\n if (Number.isNaN(absoluteTime.getTime())) {\n throw new Error(`Invalid date string provided: ${date}`);\n }\n\n return {\n absoluteTime,\n relativeTime: new Date(now.getTime() - absoluteTime.getTime()),\n };\n }\n\n throw new Error(`Unsupported date format: ${date}`);\n};\n\ntype CheckFileModifiedRangeResult = {\n isSkipped: boolean;\n message: string;\n};\n\ntype CheckFileModifiedRangeOptions = {\n skipIfModifiedBefore?: Date | number | string;\n skipIfModifiedAfter?: Date | number | string;\n};\n\nexport const checkFileModifiedRange = (\n filePath: string,\n options: CheckFileModifiedRangeOptions\n): CheckFileModifiedRangeResult => {\n const fileLastUpdateTime = checkLastUpdateTime(filePath);\n const { skipIfModifiedBefore, skipIfModifiedAfter } = options;\n\n // Normalise the provided thresholds to concrete dates.\n const now = new Date();\n const minDate = skipIfModifiedBefore\n ? normaliseInputDate(skipIfModifiedBefore, now).absoluteTime\n : undefined;\n const maxDate = skipIfModifiedAfter\n ? normaliseInputDate(skipIfModifiedAfter, now).absoluteTime\n : undefined;\n\n // Determine if the file should be skipped.\n let shouldSkip = false;\n\n if (minDate instanceof Date && maxDate instanceof Date) {\n // Skip when the modification time falls *within* the range [minDate, maxDate]\n shouldSkip = fileLastUpdateTime >= minDate && fileLastUpdateTime <= maxDate;\n } else if (minDate instanceof Date) {\n // Only lower bound – skip when the file was modified *after* minDate\n shouldSkip = fileLastUpdateTime >= minDate;\n } else if (maxDate) {\n // Only upper bound – skip when the file was modified *after* maxDate\n shouldSkip = fileLastUpdateTime >= maxDate;\n }\n\n if (shouldSkip) {\n // For the sake of the message we compute the relative time to *now* using\n // whichever bound was responsible for the skip logic.\n const referenceDate = (\n minDate && maxDate\n ? // When both bounds are present, the *range* caused the skip so we use\n // the distance between the two bounds as the relative duration.\n new Date(Math.abs(maxDate.getTime() - minDate.getTime()))\n : (minDate ?? maxDate)\n )!;\n\n const relativeTime = new Date(now.getTime() - referenceDate.getTime());\n\n return {\n isSkipped: true,\n message: `Skipping file because it has been modified within the last ${formatTimeDiff(relativeTime)} - ${filePath}`,\n };\n }\n\n return {\n isSkipped: false,\n message: `File ${filePath} can be processed - ${filePath}`,\n };\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAM,yBAAyB;;;;;;;;;;;;;;;;AAiB/B,MAAM,sBACJ,MACA,sBAAY,IAAI,KAAK,MACE;CAEvB,IAAI,gBAAgB,MAClB,OAAO;EACL,cAAc;EACd,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAK,QAAQ,CAAC;CACvD;CAIF,IAAI,OAAO,SAAS,UAAU;EAC5B,IAAI,OAAO,wBAAwB;GAEjC,MAAM,eAAe,IAAI,KAAK,IAAI;GAClC,OAAO;IACL;IACA,cAAc,IAAI,KAAK,IAAI,QAAQ,IAAI,aAAa,QAAQ,CAAC;GAC/D;EACF;EAGA,MAAM,aAAa;EACnB,OAAO;GAEL,cAAc,IAAI,KAAK,UAAU;GAEjC,cAAc,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
|
const pattern = getPatternForLocale(output, locale);
|
|
99
99
|
if (pattern === false || pattern === void 0) return false;
|
|
100
|
-
|
|
100
|
+
const rawPath = typeof pattern === "function" ? await pattern(context) : parseStringPattern(pattern, context);
|
|
101
|
+
return resolveRelativePath(rawPath, sourceFilePath, baseDir);
|
|
101
102
|
};
|
|
102
103
|
|
|
103
104
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import { parseStringPattern } from '@intlayer/config/utils';\nimport { resolveRelativePath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n\n/**\n * Get the effective FilePathPattern for a given locale from a Fill/CompilerOutput value.\n *\n * - If Fill is an object, returns the pattern for that locale (or `false` if disabled/missing).\n * - If Fill is a string/function, returns it as-is (applies to all locales).\n * - If Fill is `false`, returns `false` (disabled for all locales).\n * - If Fill is `true` or a locale entry is `true`, returns `undefined` (use default).\n */\nexport const getPatternForLocale = (\n output: Fill,\n locale: Locale\n): FilePathPattern | false | undefined => {\n if (output === false) return false;\n if (output === true) return undefined;\n if (typeof output === 'string' || typeof output === 'function')\n return output as FilePathPattern;\n if (typeof output === 'object' && output !== null) {\n const entry = (output as Record<string, boolean | FilePathPattern>)[locale];\n if (entry === undefined || entry === false) return false;\n if (entry === true) return undefined;\n return entry as FilePathPattern;\n }\n return false;\n};\n\n/**\n * Resolve a Fill/CompilerOutput pattern to an absolute file path for a given locale.\n * Returns `false` if the locale is disabled or no pattern is configured.\n */\nexport const resolveOutputPattern = async (\n output: Fill,\n locale: Locale,\n context: FilePathPatternContext,\n sourceFilePath: string,\n baseDir: string\n): Promise<string | false> => {\n const pattern = getPatternForLocale(output, locale);\n if (pattern === false || pattern === undefined) return false;\n\n const rawPath =\n typeof pattern === 'function'\n ? await pattern(context)\n : parseStringPattern(pattern, context);\n\n return resolveRelativePath(rawPath, sourceFilePath, baseDir);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,qBACX,UACA,QACA,eACW;CACX,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,YAC3B,MAAM,IAAI,MAAM,+CAA+C;CAGjE,IAAI,iBAAiB;CAGrB,MAAM,eAAe;EAEnB;GACE,SAAS;GACT,aAAa;EACf;EACA;GACE,SAAS;GACT,aAAa;EACf;EAGA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;GAC1C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,OAAO,WAAW,OAAO,GAAG;GAChD,aAAa,KAAK,OAAO;EAC3B;EAGA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,MAAM,GAAG;GAC5C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,GAAG;GAC1C,aAAa,IAAI,OAAO;EAC1B;EACA;GAEE,SAAS,IAAI,OAAO,YAAY,WAAW,IAAI,GAAG;GAClD,aAAa,KAAK,OAAO;EAC3B;EACA;GAEE,SAAS,IAAI,OAAO,MAAM,WAAW,MAAM,GAAG;GAC9C,aAAa,IAAI,OAAO;EAC1B;CACF;CAGA,KAAK,MAAM,EAAE,SAAS,iBAAiB,cACrC,iBAAiB,eAAe,QAAQ,SAAS,WAAW;CAI9D,IAAI,mBAAmB,UAAU;EAC/B,MAAM,eAAe,SAAS,YAAY,GAAG;EAC7C,IAAI,eAAe,GAEjB,OAAO,GAAG,SAAS,MAAM,GAAG,YAAY,EAAE,GAAG,SAAS,SAAS,MAAM,YAAY;OAGjF,OAAO,GAAG,SAAS,GAAG;CAE1B;CAEA,OAAO;AACT;;;;;;;;;AAUA,MAAa,uBACX,QACA,WACwC;CACxC,IAAI,WAAW,OAAO,OAAO;CAC7B,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI,OAAO,WAAW,YAAY,OAAO,WAAW,YAClD,OAAO;CACT,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM;EACjD,MAAM,QAAS,OAAqD;EACpE,IAAI,UAAU,UAAa,UAAU,OAAO,OAAO;EACnD,IAAI,UAAU,MAAM,OAAO;EAC3B,OAAO;CACT;CACA,OAAO;AACT;;;;;AAMA,MAAa,uBAAuB,OAClC,QACA,QACA,SACA,gBACA,YAC4B;CAC5B,MAAM,UAAU,oBAAoB,QAAQ,MAAM;CAClD,IAAI,YAAY,SAAS,YAAY,QAAW,OAAO;
|
|
1
|
+
{"version":3,"file":"getOutputFilePath.mjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import { parseStringPattern } from '@intlayer/config/utils';\nimport { resolveRelativePath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Get the output file path by replacing the base locale with the target locale\n *\n * This function handles two types of replacements:\n * 1. Actual locale values (e.g., `/en/` → `/fr/`)\n * 2. Template placeholders (e.g., `{{baseLocale}}` → `{{locale}}`, `{{baseLocaleName}}` → `{{localeName}}`)\n *\n * Replacement patterns:\n * - `/baseLocale/` → `/locale/`\n * - `\\baseLocale\\` → `\\locale\\`\n * - `_baseLocale.` → `_locale.`\n * - `baseLocale_` → `locale_`\n * - `.baseLocaleName.` → `.localeName.`\n * - `{{baseLocale}}` → `{{locale}}`\n * - `{{baseLocaleName}}` → `{{localeName}}`\n *\n * If no patterns match, appends `.locale` to the file extension.\n *\n * @param filePath - The input file path\n * @param locale - The target locale\n * @param baseLocale - The base locale to replace\n * @returns The output file path with locale replacements\n */\nexport const getOutputFilePath = (\n filePath: string,\n locale: LocalesValues,\n baseLocale: LocalesValues\n): string => {\n if (!filePath || !locale || !baseLocale) {\n throw new Error('filePath, locale, and baseLocale are required');\n }\n\n let outputFilePath = filePath;\n\n // Define replacement patterns with global flag to replace all occurrences\n const replacements = [\n // Template placeholders (processed first)\n {\n pattern: /\\{\\{baseLocale\\}\\}/g,\n replacement: '{{locale}}',\n },\n {\n pattern: /\\{\\{baseLocaleName\\}\\}/g,\n replacement: '{{localeName}}',\n },\n\n // Path separators (most specific first)\n {\n // Unix path separators\n pattern: new RegExp(`/${baseLocale}/`, 'g'),\n replacement: `/${locale}/`,\n },\n {\n // Windows path separators\n pattern: new RegExp(`\\\\\\\\${baseLocale}\\\\\\\\`, 'g'),\n replacement: `\\\\${locale}\\\\`,\n },\n\n // File naming patterns\n {\n // file_en.md → file_fr.md\n pattern: new RegExp(`_${baseLocale}\\\\.`, 'g'),\n replacement: `_${locale}.`,\n },\n {\n // /file_en.md → /file_fr.md\n pattern: new RegExp(`/${baseLocale}_`, 'g'),\n replacement: `/${locale}_`,\n },\n {\n // Start of filename pattern en_guide.md → fr_guide.md (or after path separator)\n pattern: new RegExp(`(^|[\\\\/])${baseLocale}_`, 'g'),\n replacement: `$1${locale}_`,\n },\n {\n // Dot delimited pattern guide.en.md → guide.fr.md\n pattern: new RegExp(`\\\\.${baseLocale}\\\\.`, 'g'),\n replacement: `.${locale}.`,\n },\n ];\n\n // Apply all replacements\n for (const { pattern, replacement } of replacements) {\n outputFilePath = outputFilePath.replace(pattern, replacement);\n }\n\n // If no changes were made, append locale as extension\n if (outputFilePath === filePath) {\n const lastDotIndex = filePath.lastIndexOf('.');\n if (lastDotIndex > 0) {\n // Insert locale before the file extension\n return `${filePath.slice(0, lastDotIndex)}.${locale}${filePath.slice(lastDotIndex)}`;\n } else {\n // No extension found, just append\n return `${filePath}.${locale}`;\n }\n }\n\n return outputFilePath;\n};\n\n/**\n * Get the effective FilePathPattern for a given locale from a Fill/CompilerOutput value.\n *\n * - If Fill is an object, returns the pattern for that locale (or `false` if disabled/missing).\n * - If Fill is a string/function, returns it as-is (applies to all locales).\n * - If Fill is `false`, returns `false` (disabled for all locales).\n * - If Fill is `true` or a locale entry is `true`, returns `undefined` (use default).\n */\nexport const getPatternForLocale = (\n output: Fill,\n locale: Locale\n): FilePathPattern | false | undefined => {\n if (output === false) return false;\n if (output === true) return undefined;\n if (typeof output === 'string' || typeof output === 'function')\n return output as FilePathPattern;\n if (typeof output === 'object' && output !== null) {\n const entry = (output as Record<string, boolean | FilePathPattern>)[locale];\n if (entry === undefined || entry === false) return false;\n if (entry === true) return undefined;\n return entry as FilePathPattern;\n }\n return false;\n};\n\n/**\n * Resolve a Fill/CompilerOutput pattern to an absolute file path for a given locale.\n * Returns `false` if the locale is disabled or no pattern is configured.\n */\nexport const resolveOutputPattern = async (\n output: Fill,\n locale: Locale,\n context: FilePathPatternContext,\n sourceFilePath: string,\n baseDir: string\n): Promise<string | false> => {\n const pattern = getPatternForLocale(output, locale);\n if (pattern === false || pattern === undefined) return false;\n\n const rawPath =\n typeof pattern === 'function'\n ? await pattern(context)\n : parseStringPattern(pattern, context);\n\n return resolveRelativePath(rawPath, sourceFilePath, baseDir);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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