@intlayer/cli 8.4.5 → 8.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cjs/fill/fill.cjs +9 -4
  2. package/dist/cjs/fill/fill.cjs.map +1 -1
  3. package/dist/cjs/fill/formatFillData.cjs +38 -34
  4. package/dist/cjs/fill/formatFillData.cjs.map +1 -1
  5. package/dist/cjs/fill/translateDictionary.cjs +2 -1
  6. package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
  7. package/dist/cjs/fill/writeFill.cjs +3 -5
  8. package/dist/cjs/fill/writeFill.cjs.map +1 -1
  9. package/dist/cjs/reviewDoc/reviewDoc.cjs +1 -1
  10. package/dist/cjs/test/listMissingTranslations.cjs +18 -4
  11. package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
  12. package/dist/cjs/translateDoc/translateDoc.cjs +1 -1
  13. package/dist/cjs/utils/getOutputFilePath.cjs +34 -0
  14. package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
  15. package/dist/esm/fill/fill.mjs +11 -6
  16. package/dist/esm/fill/fill.mjs.map +1 -1
  17. package/dist/esm/fill/formatFillData.mjs +39 -35
  18. package/dist/esm/fill/formatFillData.mjs.map +1 -1
  19. package/dist/esm/fill/translateDictionary.mjs +2 -1
  20. package/dist/esm/fill/translateDictionary.mjs.map +1 -1
  21. package/dist/esm/fill/writeFill.mjs +3 -5
  22. package/dist/esm/fill/writeFill.mjs.map +1 -1
  23. package/dist/esm/reviewDoc/reviewDoc.mjs +1 -1
  24. package/dist/esm/test/listMissingTranslations.mjs +18 -4
  25. package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
  26. package/dist/esm/translateDoc/translateDoc.mjs +1 -1
  27. package/dist/esm/utils/getOutputFilePath.mjs +33 -1
  28. package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
  29. package/dist/types/fill/fill.d.ts.map +1 -1
  30. package/dist/types/fill/formatFillData.d.ts.map +1 -1
  31. package/dist/types/test/listMissingTranslations.d.ts.map +1 -1
  32. package/dist/types/utils/getOutputFilePath.d.ts +18 -1
  33. package/dist/types/utils/getOutputFilePath.d.ts.map +1 -1
  34. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"getOutputFilePath.cjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,qBACX,UACA,QACA,eACW;AACX,KAAI,CAAC,YAAY,CAAC,UAAU,CAAC,WAC3B,OAAM,IAAI,MAAM,gDAAgD;CAGlE,IAAI,iBAAiB;CAGrB,MAAM,eAAe;EAEnB;GACE,SAAS;GACT,aAAa;GACd;EACD;GACE,SAAS;GACT,aAAa;GACd;EAGD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,IAAI;GAC3C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,OAAO,WAAW,OAAO,IAAI;GACjD,aAAa,KAAK,OAAO;GAC1B;EAGD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,MAAM,IAAI;GAC7C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,IAAI;GAC3C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,YAAY,WAAW,IAAI,IAAI;GACnD,aAAa,KAAK,OAAO;GAC1B;EACD;GAEE,SAAS,IAAI,OAAO,MAAM,WAAW,MAAM,IAAI;GAC/C,aAAa,IAAI,OAAO;GACzB;EACF;AAGD,MAAK,MAAM,EAAE,SAAS,iBAAiB,aACrC,kBAAiB,eAAe,QAAQ,SAAS,YAAY;AAI/D,KAAI,mBAAmB,UAAU;EAC/B,MAAM,eAAe,SAAS,YAAY,IAAI;AAC9C,MAAI,eAAe,EAEjB,QAAO,GAAG,SAAS,MAAM,GAAG,aAAa,CAAC,GAAG,SAAS,SAAS,MAAM,aAAa;MAGlF,QAAO,GAAG,SAAS,GAAG;;AAI1B,QAAO"}
1
+ {"version":3,"file":"getOutputFilePath.cjs","names":[],"sources":["../../../src/utils/getOutputFilePath.ts"],"sourcesContent":["import { resolveRelativePath } from '@intlayer/chokidar/utils';\nimport { parseStringPattern } from '@intlayer/config/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;AACX,KAAI,CAAC,YAAY,CAAC,UAAU,CAAC,WAC3B,OAAM,IAAI,MAAM,gDAAgD;CAGlE,IAAI,iBAAiB;CAGrB,MAAM,eAAe;EAEnB;GACE,SAAS;GACT,aAAa;GACd;EACD;GACE,SAAS;GACT,aAAa;GACd;EAGD;GAEE,SAAS,IAAI,OAAO,IAAI,WAAW,IAAI,IAAI;GAC3C,aAAa,IAAI,OAAO;GACzB;EACD;GAEE,SAAS,IAAI,OAAO,OAAO,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Q"}
@@ -3,8 +3,8 @@ import { setupAI } from "../utils/setupAI.mjs";
3
3
  import { listTranslationsTasks } from "./listTranslationsTasks.mjs";
4
4
  import { translateDictionary } from "./translateDictionary.mjs";
5
5
  import { writeFill } from "./writeFill.mjs";
6
- import { basename, relative } from "node:path";
7
- import { prepareIntlayer, writeContentDeclaration } from "@intlayer/chokidar/build";
6
+ import { basename, join, relative } from "node:path";
7
+ import { loadContentDeclarations, prepareIntlayer, writeContentDeclaration } from "@intlayer/chokidar/build";
8
8
  import { logConfigDetails } from "@intlayer/chokidar/cli";
9
9
  import { formatPath, getGlobalLimiter, getTaskLimiter } from "@intlayer/chokidar/utils";
10
10
  import * as ANSIColors from "@intlayer/config/colors";
@@ -30,6 +30,9 @@ const fill = async (options) => {
30
30
  if (!aiResult?.hasAIAccess) return;
31
31
  const { aiClient, aiConfig } = aiResult;
32
32
  const targetUnmergedDictionaries = await getTargetUnmergedDictionaries(options);
33
+ const sourceDictionaries = await loadContentDeclarations([...new Set(targetUnmergedDictionaries.map((unmergedDictionary) => unmergedDictionary.filePath).filter(Boolean))].map((sourcePath) => join(configuration.system.baseDir, sourcePath)), configuration);
34
+ const originalFillByPath = /* @__PURE__ */ new Map();
35
+ for (const dict of sourceDictionaries) if (dict.filePath) originalFillByPath.set(dict.filePath, dict.fill);
33
36
  const affectedDictionaryKeys = /* @__PURE__ */ new Set();
34
37
  targetUnmergedDictionaries.forEach((dict) => {
35
38
  affectedDictionaryKeys.add(dict.key);
@@ -49,7 +52,7 @@ const fill = async (options) => {
49
52
  const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);
50
53
  const taskLimiter = getTaskLimiter(Math.max(1, Math.min(options?.nbConcurrentTasks ?? nbConcurrentTranslations, translationTasks.length)));
51
54
  const runners = translationTasks.map((task) => taskLimiter(async () => {
52
- const relativePath = relative(configuration?.content?.baseDir ?? process.cwd(), task?.dictionaryFilePath ?? "");
55
+ const relativePath = relative(configuration?.system?.baseDir ?? process.cwd(), task?.dictionaryFilePath ?? "");
53
56
  appLogger(`${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`, { level: "info" });
54
57
  const translationTaskResult = await translateDictionary(task, configuration, {
55
58
  mode,
@@ -61,10 +64,12 @@ const fill = async (options) => {
61
64
  });
62
65
  if (!translationTaskResult?.dictionaryOutput) return;
63
66
  const { dictionaryOutput, sourceLocale } = translationTaskResult;
64
- const hasDictionaryLevelFill = typeof dictionaryOutput.fill === "string" || typeof dictionaryOutput.fill === "object";
67
+ const originalFill = originalFillByPath.get(dictionaryOutput.filePath ?? "");
68
+ const dictFill = originalFill !== void 0 ? originalFill : dictionaryOutput.fill;
69
+ const hasDictionaryLevelFill = typeof dictFill === "string" || typeof dictFill === "function" || typeof dictFill === "object" && dictFill !== null;
65
70
  const isPerLocale = typeof dictionaryOutput.locale === "string";
66
- const effectiveFill = hasDictionaryLevelFill ? dictionaryOutput.fill : isPerLocale ? configuration.dictionary?.fill ?? true : false;
67
- if (typeof effectiveFill === "string" || typeof effectiveFill === "object") await writeFill({
71
+ const effectiveFill = hasDictionaryLevelFill ? dictFill : isPerLocale ? configuration.dictionary?.fill ?? true : configuration.dictionary?.fill ?? false;
72
+ if (typeof effectiveFill === "string" || typeof effectiveFill === "function" || typeof effectiveFill === "object" && effectiveFill !== null) await writeFill({
68
73
  ...dictionaryOutput,
69
74
  fill: effectiveFill
70
75
  }, outputLocales, [sourceLocale], configuration);
@@ -1 +1 @@
1
- {"version":3,"file":"fill.mjs","names":[],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.content?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter, // <= AI calls go through here\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n // Determine if we should write to separate files\n // - If dictionary has explicit fill setting (string or object), use it\n // - If dictionary is per-locale AND has no explicit fill=false, use global fill config\n // - If dictionary is multilingual (no locale property), always write to same file\n const hasDictionaryLevelFill =\n typeof dictionaryOutput.fill === 'string' ||\n typeof dictionaryOutput.fill === 'object';\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictionaryOutput.fill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : false; // Multilingual dictionaries don't use fill by default\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' || typeof effectiveFill === 'object';\n\n if (isFillOtherFile) {\n await writeFill(\n {\n ...dictionaryOutput,\n // Ensure fill is set on the dictionary for writeFill to use\n fill: effectiveFill,\n },\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,\n { level: 'info' }\n );\n }\n }\n })\n );\n\n await Promise.all(runners);\n await (globalLimiter as any).onIdle();\n};\n"],"mappings":";;;;;;;;;;;;;;AAqCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,gBAAgB,iBAAiB,SAAS,cAAc;AAC9D,kBAAiB,SAAS,cAAc;CAExC,MAAM,YAAY,aAAa,cAAc;AAE7C,KAAI,SAAS,UAAU,KACrB,OAAM,gBAAgB,eAAe,EAAE,UAAU,MAAM,CAAC;UAC/C,OAAO,SAAS,UAAU,YACnC,OAAM,gBAAgB,cAAc;CAGtC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,gBAAgB,SAAS,gBAC3B,YAAY,QAAQ,cAAc,GAClC;CAEJ,MAAM,WAAW,MAAM,QAAQ,eAAe,SAAS,UAAU;AAEjE,KAAI,CAAC,UAAU,YAAa;CAE5B,MAAM,EAAE,UAAU,aAAa;CAE/B,MAAM,6BACJ,MAAM,8BAA8B,QAAQ;CAE9C,MAAM,yCAAyB,IAAI,KAAa;AAChD,4BAA2B,SAAS,SAAS;AA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d,cACD;OACI;AACL,SAAM,wBAAwB,kBAAkB,cAAc;AAE9D,OAAI,iBAAiB,SACnB,WACE,GAAG,KAAK,iBAAiB,kCAAkC,WAAW,SAAS,iBAAiB,SAAS,CAAC,IAC1G,EAAE,OAAO,QAAQ,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
1
+ {"version":3,"file":"fill.mjs","names":[],"sources":["../../../src/fill/fill.ts"],"sourcesContent":["import { basename, join, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n loadContentDeclarations,\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatPath,\n getGlobalLimiter,\n getTaskLimiter,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { Fill } from '@intlayer/types/dictionary';\nimport {\n ensureArray,\n type GetTargetDictionaryOptions,\n getTargetUnmergedDictionaries,\n} from '../getTargetDictionary';\nimport { setupAI } from '../utils/setupAI';\nimport {\n listTranslationsTasks,\n type TranslationTask,\n} from './listTranslationsTasks';\nimport { translateDictionary } from './translateDictionary';\nimport { writeFill } from './writeFill';\n\nconst NB_CONCURRENT_TRANSLATIONS = 7;\n\n// Arguments for the fill function\nexport type FillOptions = {\n sourceLocale?: Locale;\n outputLocales?: Locale | Locale[];\n mode?: 'complete' | 'review';\n gitOptions?: ListGitFilesOptions;\n aiOptions?: AIOptions; // Added aiOptions to be passed to translateJSON\n verbose?: boolean;\n nbConcurrentTranslations?: number;\n nbConcurrentTasks?: number; // NEW: number of tasks that may run at once\n build?: boolean;\n skipMetadata?: boolean;\n} & GetTargetDictionaryOptions;\n\n/**\n * Fill translations based on the provided options.\n */\nexport const fill = async (options?: FillOptions): Promise<void> => {\n const configuration = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n if (options?.build === true) {\n await prepareIntlayer(configuration, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(configuration);\n }\n\n const { defaultLocale, locales } = configuration.internationalization;\n const mode = options?.mode ?? 'complete';\n const baseLocale = options?.sourceLocale ?? defaultLocale;\n\n const outputLocales = options?.outputLocales\n ? ensureArray(options.outputLocales)\n : locales;\n\n const aiResult = await setupAI(configuration, options?.aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n const targetUnmergedDictionaries =\n await getTargetUnmergedDictionaries(options);\n\n // Load the original source content declaration files to recover function-type\n // `fill` values that are lost when dictionaries are JSON-serialised into\n // unmerged_dictionaries.cjs. Dictionary-level fill takes priority over the\n // config-level fill, but we can only know that by reading the source files.\n const uniqueSourcePaths = [\n ...new Set(\n targetUnmergedDictionaries\n .map((unmergedDictionary) => unmergedDictionary.filePath)\n .filter(Boolean) as string[]\n ),\n ];\n const sourceDictionaries = await loadContentDeclarations(\n uniqueSourcePaths.map((sourcePath) =>\n join(configuration.system.baseDir, sourcePath)\n ),\n configuration\n );\n // Map relative filePath → original fill value from the source file\n const originalFillByPath = new Map<string, Fill | undefined>();\n\n for (const dict of sourceDictionaries) {\n if (dict.filePath) {\n originalFillByPath.set(dict.filePath, dict.fill as Fill | undefined);\n }\n }\n\n const affectedDictionaryKeys = new Set<string>();\n targetUnmergedDictionaries.forEach((dict) => {\n affectedDictionaryKeys.add(dict.key);\n });\n\n const keysToProcess = Array.from(affectedDictionaryKeys);\n\n appLogger([\n 'Affected dictionary keys for processing:',\n keysToProcess.length > 0\n ? keysToProcess.map((key) => colorizeKey(key)).join(', ')\n : colorize('No keys found', ANSIColors.YELLOW),\n ]);\n\n if (keysToProcess.length === 0) return;\n\n /**\n * List the translations tasks\n *\n * Create a list of per-locale dictionaries to translate\n *\n * In 'complete' mode, filter only the missing locales to translate\n */\n const translationTasks: TranslationTask[] = listTranslationsTasks(\n targetUnmergedDictionaries.map((dictionary) => dictionary.localId!),\n outputLocales,\n mode,\n baseLocale,\n configuration\n );\n\n // AI calls in flight at once (translateJSON + metadata audit)\n const nbConcurrentTranslations =\n options?.nbConcurrentTranslations ?? NB_CONCURRENT_TRANSLATIONS;\n const globalLimiter = getGlobalLimiter(nbConcurrentTranslations);\n\n // NEW: number of *tasks* that may run at once (start/prepare/log/write)\n const nbConcurrentTasks = Math.max(\n 1,\n Math.min(\n options?.nbConcurrentTasks ?? nbConcurrentTranslations,\n translationTasks.length\n )\n );\n\n const taskLimiter = getTaskLimiter(nbConcurrentTasks);\n\n const runners = translationTasks.map((task) =>\n taskLimiter(async () => {\n const relativePath = relative(\n configuration?.system?.baseDir ?? process.cwd(),\n task?.dictionaryFilePath ?? ''\n );\n\n // log AFTER acquiring a task slot\n appLogger(\n `${task.dictionaryPreset} Processing ${colorizePath(basename(relativePath))}`,\n { level: 'info' }\n );\n\n const translationTaskResult = await translateDictionary(\n task,\n configuration,\n {\n mode,\n aiOptions: options?.aiOptions,\n fillMetadata: !options?.skipMetadata,\n onHandle: globalLimiter,\n aiClient,\n aiConfig,\n }\n );\n\n if (!translationTaskResult?.dictionaryOutput) return;\n\n const { dictionaryOutput, sourceLocale } = translationTaskResult;\n\n // Determine if we should write to separate files\n // - If dictionary has explicit fill setting (string, function, or object), use it\n // - If dictionary is per-locale AND has no explicit fill=false, use global fill config\n // - If dictionary is multilingual (no locale property), always write to same file\n //\n // NOTE: function-type fill values are lost during JSON serialisation of\n // unmerged_dictionaries.cjs. We recover them by checking the original\n // source file that was loaded above (originalFillByPath). Dictionary-level\n // fill always takes priority over config-level fill.\n const originalFill = originalFillByPath.get(\n dictionaryOutput.filePath ?? ''\n );\n\n // originalFill is undefined when the source file had no fill property; use\n // the (possibly JSON-preserved) dictionaryOutput.fill as a fallback so that\n // string/boolean fill values set directly on the dict still work.\n const dictFill: Fill | undefined =\n originalFill !== undefined ? originalFill : dictionaryOutput.fill;\n\n const hasDictionaryLevelFill =\n typeof dictFill === 'string' ||\n typeof dictFill === 'function' ||\n (typeof dictFill === 'object' && dictFill !== null);\n\n const isPerLocale = typeof dictionaryOutput.locale === 'string';\n\n const effectiveFill = hasDictionaryLevelFill\n ? dictFill\n : isPerLocale\n ? (configuration.dictionary?.fill ?? true)\n : (configuration.dictionary?.fill ?? false); // Multilingual dictionaries use config-level fill if set\n\n const isFillOtherFile =\n typeof effectiveFill === 'string' ||\n typeof effectiveFill === 'function' ||\n (typeof effectiveFill === 'object' && effectiveFill !== null);\n\n if (isFillOtherFile) {\n await writeFill(\n {\n ...dictionaryOutput,\n // Ensure fill is set on the dictionary for writeFill to use\n fill: effectiveFill,\n },\n outputLocales,\n [sourceLocale],\n configuration\n );\n } else {\n await writeContentDeclaration(dictionaryOutput, configuration);\n\n if (dictionaryOutput.filePath) {\n appLogger(\n `${task.dictionaryPreset} Content declaration written to ${formatPath(basename(dictionaryOutput.filePath))}`,\n { level: 'info' }\n );\n }\n }\n })\n );\n\n await Promise.all(runners);\n await (globalLimiter as any).onIdle();\n};\n"],"mappings":";;;;;;;;;;;;;;AAuCA,MAAM,6BAA6B;;;;AAmBnC,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,gBAAgB,iBAAiB,SAAS,cAAc;AAC9D,kBAAiB,SAAS,cAAc;CAExC,MAAM,YAAY,aAAa,cAAc;AAE7C,KAAI,SAAS,UAAU,KACrB,OAAM,gBAAgB,eAAe,EAAE,UAAU,MAAM,CAAC;UAC/C,OAAO,SAAS,UAAU,YACnC,OAAM,gBAAgB,cAAc;CAGtC,MAAM,EAAE,eAAe,YAAY,cAAc;CACjD,MAAM,OAAO,SAAS,QAAQ;CAC9B,MAAM,aAAa,SAAS,gBAAgB;CAE5C,MAAM,gBAAgB,SAAS,gBAC3B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iBAAiB,cAAc,aAAa,SAAS,aAAa,CAAC,IAC3E,EAAE,OAAO,QAAQ,CAClB;EAED,MAAM,wBAAwB,MAAM,oBAClC,MACA,eACA;GACE;GACA,WAAW,SAAS;GACpB,cAAc,CAAC,SAAS;GACxB,UAAU;GACV;GACA;GACD,CACF;AAED,MAAI,CAAC,uBAAuB,iBAAkB;EAE9C,MAAM,EAAE,kBAAkB,iBAAiB;EAW3C,MAAM,eAAe,mBAAmB,IACtC,iBAAiB,YAAY,GAC9B;EAKD,MAAM,WACJ,iBAAiB,SAAY,eAAe,iBAAiB;EAE/D,MAAM,yBACJ,OAAO,aAAa,YACpB,OAAO,aAAa,cACnB,OAAO,aAAa,YAAY,aAAa;EAEhD,MAAM,cAAc,OAAO,iBAAiB,WAAW;EAEvD,MAAM,gBAAgB,yBAClB,WACA,cACG,cAAc,YAAY,QAAQ,OAClC,cAAc,YAAY,QAAQ;AAOzC,MAJE,OAAO,kBAAkB,YACzB,OAAO,kBAAkB,cACxB,OAAO,kBAAkB,YAAY,kBAAkB,KAGxD,OAAM,UACJ;GACE,GAAG;GAEH,MAAM;GACP,EACD,eACA,CAAC,aAAa,EACd,cACD;OACI;AACL,SAAM,wBAAwB,kBAAkB,cAAc;AAE9D,OAAI,iBAAiB,SACnB,WACE,GAAG,KAAK,iBAAiB,kCAAkC,WAAW,SAAS,iBAAiB,SAAS,CAAC,IAC1G,EAAE,OAAO,QAAQ,CAClB;;GAGL,CACH;AAED,OAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAO,cAAsB,QAAQ"}
@@ -1,8 +1,17 @@
1
+ import { getPatternForLocale, resolveOutputPattern } from "../utils/getOutputFilePath.mjs";
1
2
  import { basename, dirname, extname, relative } from "node:path";
2
- import { getFormatFromExtension, resolveRelativePath } from "@intlayer/chokidar/utils";
3
- import { parseStringPattern } from "@intlayer/config/utils";
3
+ import { getFormatFromExtension } from "@intlayer/chokidar/utils";
4
4
 
5
5
  //#region src/fill/formatFillData.ts
6
+ /** Merge FillData entries that resolve to the same file path. */
7
+ const groupByFilePath = (entries) => entries.reduce((acc, curr) => {
8
+ const existing = acc.find((item) => item.filePath === curr.filePath);
9
+ if (existing) {
10
+ for (const loc of curr.localeList) if (!existing.localeList.includes(loc)) existing.localeList.push(loc);
11
+ existing.isPerLocale = false;
12
+ } else acc.push(curr);
13
+ return acc;
14
+ }, []);
6
15
  const formatFillData = async (fillField, localeList, filePath, dictionaryKey, configuration) => {
7
16
  if (!fillField || typeof fillField === "boolean") return [];
8
17
  const { baseDir } = configuration.system;
@@ -12,10 +21,10 @@ const formatFillData = async (fillField, localeList, filePath, dictionaryKey, co
12
21
  const cleanComponentFileName = base.includes(".content.") ? base.split(".content.")[0] : base.split(".")[0];
13
22
  const uncapitalizedName = cleanComponentFileName.charAt(0).toLowerCase() + cleanComponentFileName.slice(1);
14
23
  const componentFormat = getFormatFromExtension(extension);
15
- const getContext = (locale, patternType) => {
24
+ const getContext = (locale, patternString) => {
16
25
  let format = "json";
17
- if (typeof patternType === "string") {
18
- const extFormat = getFormatFromExtension(extname(patternType));
26
+ if (patternString) {
27
+ const extFormat = getFormatFromExtension(extname(patternString));
19
28
  if (extFormat) format = extFormat;
20
29
  }
21
30
  return {
@@ -30,31 +39,34 @@ const formatFillData = async (fillField, localeList, filePath, dictionaryKey, co
30
39
  extension: configuration.content.fileExtensions[0]
31
40
  };
32
41
  };
33
- const processPattern = async (pattern, locales) => {
42
+ /**
43
+ * Evaluate a scalar Fill pattern (string or function) for a list of locales.
44
+ *
45
+ * - Uses a dummy locale probe to detect whether the pattern varies per locale.
46
+ * - `forcePerLocale` overrides the probe for object-fill entries where each
47
+ * locale always maps to its own dedicated file regardless of whether the
48
+ * path itself contains the locale string.
49
+ */
50
+ const processPattern = async (pattern, locales, forcePerLocale = false) => {
34
51
  const dummyLocale = "###########locale###########";
35
- let isPatternPerLocale = false;
36
- if (typeof pattern === "string") isPatternPerLocale = pattern.includes("{{locale}}");
37
- else if (typeof pattern === "function") isPatternPerLocale = (await pattern(getContext(dummyLocale, pattern))).includes(dummyLocale);
38
- if (isPatternPerLocale) {
52
+ const patternString = typeof pattern === "string" ? pattern : void 0;
53
+ const dummyPath = await resolveOutputPattern(pattern, dummyLocale, getContext(dummyLocale, patternString), filePath, baseDir);
54
+ if (forcePerLocale || typeof dummyPath === "string" && dummyPath.includes(dummyLocale)) {
39
55
  const resolvedPaths = [];
40
56
  for (const locale of locales) {
41
- const absolutePath = resolveRelativePath(typeof pattern === "string" ? parseStringPattern(pattern, getContext(locale, pattern)) : await pattern(getContext(locale, pattern)), filePath, baseDir);
42
- resolvedPaths.push({
57
+ const absolutePath = await resolveOutputPattern(pattern, locale, getContext(locale, patternString), filePath, baseDir);
58
+ if (absolutePath !== false) resolvedPaths.push({
43
59
  filePath: absolutePath,
44
60
  localeList: [locale],
45
61
  isPerLocale: true
46
62
  });
47
63
  }
48
- return resolvedPaths.reduce((acc, curr) => {
49
- const existing = acc.find((item) => item.filePath === curr.filePath);
50
- if (existing) {
51
- if (!existing.localeList.includes(curr.localeList[0])) existing.localeList.push(...curr.localeList);
52
- existing.isPerLocale = false;
53
- } else acc.push(curr);
54
- return acc;
55
- }, []);
56
- } else return [{
57
- filePath: resolveRelativePath(typeof pattern === "string" ? parseStringPattern(pattern, getContext(defaultLocale, pattern)) : await pattern(getContext(defaultLocale, pattern)), filePath, baseDir),
64
+ return groupByFilePath(resolvedPaths);
65
+ }
66
+ const absolutePath = await resolveOutputPattern(pattern, defaultLocale, getContext(defaultLocale, patternString), filePath, baseDir);
67
+ if (absolutePath === false) return [];
68
+ return [{
69
+ filePath: absolutePath,
58
70
  localeList: locales,
59
71
  isPerLocale: false
60
72
  }];
@@ -62,23 +74,15 @@ const formatFillData = async (fillField, localeList, filePath, dictionaryKey, co
62
74
  if (typeof fillField === "object" && fillField !== null) {
63
75
  const results = [];
64
76
  for (const locale of localeList) {
65
- const pattern = fillField[locale];
66
- if (pattern && typeof pattern !== "boolean") {
67
- const res = await processPattern(pattern, [locale]);
77
+ const pattern = getPatternForLocale(fillField, locale);
78
+ if (pattern) {
79
+ const res = await processPattern(pattern, [locale], true);
68
80
  results.push(...res);
69
81
  }
70
82
  }
71
- return results.reduce((acc, curr) => {
72
- const existing = acc.find((item) => item.filePath === curr.filePath);
73
- if (existing) {
74
- for (const loc of curr.localeList) if (!existing.localeList.includes(loc)) existing.localeList.push(loc);
75
- existing.isPerLocale = false;
76
- } else acc.push(curr);
77
- return acc;
78
- }, []);
83
+ return groupByFilePath(results);
79
84
  }
80
- if (typeof fillField === "string" || typeof fillField === "function") return processPattern(fillField, localeList);
81
- return [];
85
+ return processPattern(fillField, localeList);
82
86
  };
83
87
 
84
88
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"formatFillData.mjs","names":[],"sources":["../../../src/fill/formatFillData.ts"],"sourcesContent":["import { basename, dirname, extname, relative } from 'node:path';\nimport {\n getFormatFromExtension,\n resolveRelativePath,\n} from '@intlayer/chokidar/utils';\nimport { parseStringPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { DictionaryKey, Fill } from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\n\nexport type FillData = {\n localeList: Locale[];\n filePath: string;\n isPerLocale: boolean;\n};\n\nexport const formatFillData = async (\n fillField: Fill,\n localeList: Locale[],\n filePath: string,\n dictionaryKey: DictionaryKey,\n configuration: IntlayerConfig\n): Promise<FillData[]> => {\n if (!fillField || typeof fillField === 'boolean') return [];\n\n const { baseDir } = configuration.system;\n const { defaultLocale } = configuration.internationalization;\n\n const extension = extname(filePath);\n const base = basename(filePath);\n\n // Extract the original filename without extensions\n const cleanComponentFileName = base.includes('.content.')\n ? base.split('.content.')[0]\n : base.split('.')[0];\n\n const uncapitalizedName =\n cleanComponentFileName.charAt(0).toLowerCase() +\n cleanComponentFileName.slice(1);\n\n const componentFormat = getFormatFromExtension(extension);\n\n const getContext = (\n locale: Locale,\n patternType?: FilePathPattern\n ): FilePathPatternContext => {\n let format: FilePathPatternContext['format'] = 'json';\n if (typeof patternType === 'string') {\n const extFormat = getFormatFromExtension(extname(patternType) as any);\n if (extFormat) {\n format = extFormat as any;\n }\n }\n\n return {\n key: dictionaryKey,\n componentDirPath: relative(baseDir, dirname(filePath)),\n componentFileName: cleanComponentFileName,\n fileName: uncapitalizedName,\n componentFormat:\n componentFormat as FilePathPatternContext['componentFormat'],\n componentExtension:\n extension as FilePathPatternContext['componentExtension'],\n format,\n locale,\n extension: configuration.content.fileExtensions[0],\n };\n };\n\n const processPattern = async (\n pattern: FilePathPattern,\n locales: Locale[]\n ): Promise<FillData[]> => {\n const dummyLocale = '###########locale###########' as Locale;\n let isPatternPerLocale = false;\n\n if (typeof pattern === 'string') {\n isPatternPerLocale = pattern.includes('{{locale}}');\n } else if (typeof pattern === 'function') {\n const pathWithDummy = await pattern(getContext(dummyLocale, pattern));\n isPatternPerLocale = pathWithDummy.includes(dummyLocale);\n }\n\n if (isPatternPerLocale) {\n const resolvedPaths: FillData[] = [];\n\n // Generate one path per locale\n for (const locale of locales) {\n const rawPath =\n typeof pattern === 'string'\n ? parseStringPattern(pattern, getContext(locale, pattern))\n : await pattern(getContext(locale, pattern));\n\n const absolutePath = resolveRelativePath(rawPath, filePath, baseDir);\n\n resolvedPaths.push({\n filePath: absolutePath,\n localeList: [locale],\n isPerLocale: true,\n });\n }\n\n // Group by filePath in case multiple locales resolve to the same path\n const groupedByFilePath = resolvedPaths.reduce((acc, curr) => {\n const existing = acc.find((item) => item.filePath === curr.filePath);\n if (existing) {\n if (!existing.localeList.includes(curr.localeList[0])) {\n existing.localeList.push(...curr.localeList);\n }\n // If multiple locales share a path, it's no longer strictly per-locale\n existing.isPerLocale = false;\n } else {\n acc.push(curr);\n }\n return acc;\n }, [] as FillData[]);\n\n return groupedByFilePath;\n } else {\n // Single multi-lingual path using default locale for pattern resolution\n const rawPath =\n typeof pattern === 'string'\n ? parseStringPattern(pattern, getContext(defaultLocale, pattern))\n : await pattern(getContext(defaultLocale, pattern));\n\n const absolutePath = resolveRelativePath(rawPath, filePath, baseDir);\n\n return [\n {\n filePath: absolutePath,\n localeList: locales,\n isPerLocale: false,\n },\n ];\n }\n };\n\n // Handle Record of Locales\n if (typeof fillField === 'object' && fillField !== null) {\n const results: FillData[] = [];\n\n for (const locale of localeList) {\n const pattern = (fillField as Record<string, any>)[locale];\n if (pattern && typeof pattern !== 'boolean') {\n const res = await processPattern(pattern as FilePathPattern, [locale]);\n results.push(...res);\n }\n }\n\n // Merge identical file paths if they stem from different locales having the same output path\n const grouped = results.reduce((acc, curr) => {\n const existing = acc.find((item) => item.filePath === curr.filePath);\n if (existing) {\n for (const loc of curr.localeList) {\n if (!existing.localeList.includes(loc)) {\n existing.localeList.push(loc);\n }\n }\n existing.isPerLocale = false;\n } else {\n acc.push(curr);\n }\n return acc;\n }, [] as FillData[]);\n\n return grouped;\n }\n\n // Handle static string or function patterns\n if (typeof fillField === 'string' || typeof fillField === 'function') {\n return processPattern(fillField as FilePathPattern, localeList);\n }\n\n return [];\n};\n"],"mappings":";;;;;AAoBA,MAAa,iBAAiB,OAC5B,WACA,YACA,UACA,eACA,kBACwB;AACxB,KAAI,CAAC,aAAa,OAAO,cAAc,UAAW,QAAO,EAAE;CAE3D,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,kBAAkB,cAAc;CAExC,MAAM,YAAY,QAAQ,SAAS;CACnC,MAAM,OAAO,SAAS,SAAS;CAG/B,MAAM,yBAAyB,KAAK,SAAS,YAAY,GACrD,KAAK,MAAM,YAAY,CAAC,KACxB,KAAK,MAAM,IAAI,CAAC;CAEpB,MAAM,oBACJ,uBAAuB,OAAO,EAAE,CAAC,aAAa,GAC9C,uBAAuB,MAAM,EAAE;CAEjC,MAAM,kBAAkB,uBAAuB,UAAU;CAEzD,MAAM,cACJ,QACA,gBAC2B;EAC3B,IAAI,SAA2C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L,UAAU,QAAQ;GAKhE,YAAY;GACZ,aAAa;GACd,CACF;;AAKL,KAAI,OAAO,cAAc,YAAY,cAAc,MAAM;EACvD,MAAM,UAAsB,EAAE;AAE9B,OAAK,MAAM,UAAU,YAAY;GAC/B,MAAM,UAAW,UAAkC;AACnD,OAAI,WAAW,OAAO,YAAY,WAAW;IAC3C,MAAM,MAAM,MAAM,eAAe,SAA4B,CAAC,OAAO,CAAC;AACtE,YAAQ,KAAK,GAAG,IAAI;;;AAoBxB,SAfgB,QAAQ,QAAQ,KAAK,SAAS;GAC5C,MAAM,WAAW,IAAI,MAAM,SAAS,KAAK,aAAa,KAAK,SAAS;AACpE,OAAI,UAAU;AACZ,SAAK,MAAM,OAAO,KAAK,WACrB,KAAI,CAAC,SAAS,WAAW,SAAS,IAAI,CACpC,UAAS,WAAW,KAAK,IAAI;AAGjC,aAAS,cAAc;SAEvB,KAAI,KAAK,KAAK;AAEhB,UAAO;KACN,EAAE,CAAe;;AAMtB,KAAI,OAAO,cAAc,YAAY,OAAO,cAAc,WACxD,QAAO,eAAe,WAA8B,WAAW;AAGjE,QAAO,EAAE"}
1
+ {"version":3,"file":"formatFillData.mjs","names":[],"sources":["../../../src/fill/formatFillData.ts"],"sourcesContent":["import { basename, dirname, extname, relative } from 'node:path';\nimport { getFormatFromExtension } from '@intlayer/chokidar/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { DictionaryKey, Fill } from '@intlayer/types/dictionary';\nimport type { FilePathPatternContext } from '@intlayer/types/filePathPattern';\nimport {\n getPatternForLocale,\n resolveOutputPattern,\n} from '../utils/getOutputFilePath';\n\nexport type FillData = {\n localeList: Locale[];\n filePath: string;\n isPerLocale: boolean;\n};\n\n/** Merge FillData entries that resolve to the same file path. */\nconst groupByFilePath = (entries: FillData[]): FillData[] =>\n entries.reduce((acc, curr) => {\n const existing = acc.find((item) => item.filePath === curr.filePath);\n if (existing) {\n for (const loc of curr.localeList) {\n if (!existing.localeList.includes(loc)) existing.localeList.push(loc);\n }\n // Multiple locales sharing one path → multilingual file\n existing.isPerLocale = false;\n } else {\n acc.push(curr);\n }\n return acc;\n }, [] as FillData[]);\n\nexport const formatFillData = async (\n fillField: Fill,\n localeList: Locale[],\n filePath: string,\n dictionaryKey: DictionaryKey,\n configuration: IntlayerConfig\n): Promise<FillData[]> => {\n if (!fillField || typeof fillField === 'boolean') return [];\n\n const { baseDir } = configuration.system;\n const { defaultLocale } = configuration.internationalization;\n\n const extension = extname(filePath);\n const base = basename(filePath);\n const cleanComponentFileName = base.includes('.content.')\n ? base.split('.content.')[0]\n : base.split('.')[0];\n const uncapitalizedName =\n cleanComponentFileName.charAt(0).toLowerCase() +\n cleanComponentFileName.slice(1);\n const componentFormat = getFormatFromExtension(extension);\n\n const getContext = (\n locale: Locale,\n patternString?: string\n ): FilePathPatternContext => {\n let format: FilePathPatternContext['format'] = 'json';\n if (patternString) {\n const extFormat = getFormatFromExtension(extname(patternString) as any);\n if (extFormat) format = extFormat as any;\n }\n return {\n key: dictionaryKey,\n componentDirPath: relative(baseDir, dirname(filePath)),\n componentFileName: cleanComponentFileName,\n fileName: uncapitalizedName,\n componentFormat:\n componentFormat as FilePathPatternContext['componentFormat'],\n componentExtension:\n extension as FilePathPatternContext['componentExtension'],\n format,\n locale,\n extension: configuration.content.fileExtensions[0],\n };\n };\n\n /**\n * Evaluate a scalar Fill pattern (string or function) for a list of locales.\n *\n * - Uses a dummy locale probe to detect whether the pattern varies per locale.\n * - `forcePerLocale` overrides the probe for object-fill entries where each\n * locale always maps to its own dedicated file regardless of whether the\n * path itself contains the locale string.\n */\n const processPattern = async (\n pattern: Fill,\n locales: Locale[],\n forcePerLocale = false\n ): Promise<FillData[]> => {\n const dummyLocale = '###########locale###########' as Locale;\n const patternString = typeof pattern === 'string' ? pattern : undefined;\n\n const dummyPath = await resolveOutputPattern(\n pattern,\n dummyLocale,\n getContext(dummyLocale, patternString),\n filePath,\n baseDir\n );\n const isPatternPerLocale =\n forcePerLocale ||\n (typeof dummyPath === 'string' && dummyPath.includes(dummyLocale));\n\n if (isPatternPerLocale) {\n const resolvedPaths: FillData[] = [];\n for (const locale of locales) {\n const absolutePath = await resolveOutputPattern(\n pattern,\n locale,\n getContext(locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath !== false) {\n resolvedPaths.push({\n filePath: absolutePath,\n localeList: [locale],\n isPerLocale: true,\n });\n }\n }\n return groupByFilePath(resolvedPaths);\n }\n\n // Single multilingual path resolve using the default locale for context\n const absolutePath = await resolveOutputPattern(\n pattern,\n defaultLocale as Locale,\n getContext(defaultLocale as Locale, patternString),\n filePath,\n baseDir\n );\n if (absolutePath === false) return [];\n return [\n { filePath: absolutePath, localeList: locales, isPerLocale: false },\n ];\n };\n\n // Object fill: each locale key maps to its own pattern.\n // Object fill entries are always per-locale in intent (each locale → its own file).\n if (typeof fillField === 'object' && fillField !== null) {\n const results: FillData[] = [];\n for (const locale of localeList) {\n const pattern = getPatternForLocale(fillField, locale);\n if (pattern) {\n const res = await processPattern(pattern, [locale], true);\n results.push(...res);\n }\n }\n return groupByFilePath(results);\n }\n\n // Scalar string or function pattern\n return processPattern(fillField, localeList);\n};\n"],"mappings":";;;;;;AAkBA,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,KAAK,SAAS;CAC5B,MAAM,WAAW,IAAI,MAAM,SAAS,KAAK,aAAa,KAAK,SAAS;AACpE,KAAI,UAAU;AACZ,OAAK,MAAM,OAAO,KAAK,WACrB,KAAI,CAAC,SAAS,WAAW,SAAS,IAAI,CAAE,UAAS,WAAW,KAAK,IAAI;AAGvE,WAAS,cAAc;OAEvB,KAAI,KAAK,KAAK;AAEhB,QAAO;GACN,EAAE,CAAe;AAEtB,MAAa,iBAAiB,OAC5B,WACA,YACA,UACA,eACA,kBACwB;AACxB,KAAI,CAAC,aAAa,OAAO,cAAc,UAAW,QAAO,EAAE;CAE3D,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM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rC,SAAO,CACL;GAAE,UAAU;GAAc,YAAY;GAAS,aAAa;GAAO,CACpE;;AAKH,KAAI,OAAO,cAAc,YAAY,cAAc,MAAM;EACvD,MAAM,UAAsB,EAAE;AAC9B,OAAK,MAAM,UAAU,YAAY;GAC/B,MAAM,UAAU,oBAAoB,WAAW,OAAO;AACtD,OAAI,SAAS;IACX,MAAM,MAAM,MAAM,eAAe,SAAS,CAAC,OAAO,EAAE,KAAK;AACzD,YAAQ,KAAK,GAAG,IAAI;;;AAGxB,SAAO,gBAAgB,QAAQ;;AAIjC,QAAO,eAAe,WAAW,WAAW"}
@@ -209,7 +209,8 @@ const translateDictionary = async (task, configuration, options) => {
209
209
  };
210
210
  for (const targetLocale of task.targetLocales) if (translatedContent[targetLocale]) dictionaryOutput = insertContentInDictionary(dictionaryOutput, translatedContent[targetLocale], targetLocale);
211
211
  appLogger(`${task.dictionaryPreset} ${colorize("Translation completed successfully", ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath))}`, { level: "info" });
212
- if (baseUnmergedDictionary.locale && (baseUnmergedDictionary.fill === true || baseUnmergedDictionary.fill === void 0) && baseUnmergedDictionary.location === "local") {
212
+ const effectiveFillForCheck = baseUnmergedDictionary.fill ?? configuration.dictionary?.fill;
213
+ if (baseUnmergedDictionary.locale && (effectiveFillForCheck === true || effectiveFillForCheck === void 0) && baseUnmergedDictionary.location === "local") {
213
214
  const dictionaryFilePath = baseUnmergedDictionary.filePath.split(".").slice(0, -1);
214
215
  const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];
215
216
  return JSON.parse(JSON.stringify({
@@ -1 +1 @@
1
- {"version":3,"file":"translateDictionary.mjs","names":[],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport { getFilterMissingContentPerLocale } from './getFilterMissingContentPerLocale';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<\n typeof import('@intlayer/chokidar/utils').getGlobalLimiter\n >;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\n/**\n * Recursively strips null values from an object, returning the cleaned content\n * and a separate object containing only the null-valued paths so they can be\n * re-injected after AI translation (nulls don't need translation).\n */\nconst stripNullValues = (\n obj: any\n): { content: any; nulls: any; hasNulls: boolean } => {\n if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {\n return { content: obj, nulls: undefined, hasNulls: false };\n }\n\n const content: any = {};\n const nulls: any = {};\n let hasNulls = false;\n\n for (const [key, value] of Object.entries(obj)) {\n if (value === null) {\n nulls[key] = null;\n hasNulls = true;\n } else {\n const child = stripNullValues(value);\n content[key] = child.content;\n if (child.hasNulls) {\n nulls[key] = child.nulls;\n hasNulls = true;\n }\n }\n }\n\n return { content, nulls: hasNulls ? nulls : undefined, hasNulls };\n};\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // For per-locale files, the content is already in simple JSON format (not translation nodes)\n // The base dictionary is already the source locale content\n\n // Load the existing target locale dictionary\n const targetLocaleFilePath =\n baseUnmergedDictionary.filePath?.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n );\n\n // Find the target locale dictionary in unmerged dictionaries\n const targetUnmergedDictionary = targetLocaleFilePath\n ? unmergedDictionariesRecord[task.dictionaryKey]?.find(\n (dict) =>\n dict.filePath === targetLocaleFilePath &&\n dict.locale === targetLocale\n )\n : undefined;\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: targetLocaleFilePath,\n locale: targetLocale,\n };\n\n // In complete mode, filter out already translated content\n if (mode === 'complete') {\n dictionaryToProcess = getFilterMissingContentPerLocale(\n dictionaryToProcess,\n targetUnmergedDictionary\n );\n }\n } else {\n // For multilingual dictionaries\n if (mode === 'complete') {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const isContentStructured =\n (typeof dictionaryToProcess.content === 'object' &&\n dictionaryToProcess.content !== null) ||\n Array.isArray(dictionaryToProcess.content);\n\n const rawContentToProcess = isContentStructured\n ? dictionaryToProcess.content\n : {\n __INTLAYER_ROOT_PRIMITIVE_CONTENT__:\n dictionaryToProcess.content,\n };\n\n // Strip null values before sending to AI — nulls need no translation\n // and confuse the model. They will be re-injected after merging.\n const { content: contentToProcess, nulls: strippedNullValues } =\n stripNullValues(rawContentToProcess);\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n contentToProcess as unknown as Record<string, any>,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n isContentStructured\n ? targetLocaleDictionary.content\n : {\n __INTLAYER_ROOT_PRIMITIVE_CONTENT__:\n targetLocaleDictionary.content,\n },\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n\n if (!isIdentic) {\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n let mergedContent = mergeChunks(chunkResult);\n\n // Re-inject null values that were stripped before AI translation\n if (strippedNullValues) {\n mergedContent = deepMergeContent(mergedContent, strippedNullValues);\n }\n\n const merged = {\n ...dictionaryToProcess,\n content: mergedContent,\n };\n\n // For per-locale files, merge the newly translated content with existing target content\n let finalContent = merged.content;\n\n if (!isContentStructured) {\n finalContent = (finalContent as any)\n ?.__INTLAYER_ROOT_PRIMITIVE_CONTENT__;\n }\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // Deep merge: existing content + newly translated content\n finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n finalContent\n );\n }\n\n return [targetLocale, finalContent] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n if (\n baseUnmergedDictionary.locale &&\n (baseUnmergedDictionary.fill === true ||\n baseUnmergedDictionary.fill === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;;;AAsDA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;;;;;;AAO9D,MAAM,mBACJ,QACoD;AACpD,KAAI,OAAO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AQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,CAAC,aAAa,eAAe,UAAU,EAAE,CAAC,MAAM,eAAe,SAAS,IACnO,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,GAAG,SAAS,sCAAsC,WAAW,IAAI,CAAC,GAAG,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,IACvL,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
1
+ {"version":3,"file":"translateDictionary.mjs","names":[],"sources":["../../../src/fill/translateDictionary.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport type { AIConfig } from '@intlayer/ai';\nimport { type AIOptions, getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n chunkJSON,\n formatLocale,\n type JsonChunk,\n mergeChunks,\n reconstructFromSingleChunk,\n reduceObjectFormat,\n verifyIdenticObjectFormat,\n} from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport {\n getFilterMissingTranslationsDictionary,\n getMultilingualDictionary,\n getPerLocaleDictionary,\n insertContentInDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport type { AIClient } from '../utils/setupAI';\nimport { deepMergeContent } from './deepMergeContent';\nimport { getFilterMissingContentPerLocale } from './getFilterMissingContentPerLocale';\nimport type { TranslationTask } from './listTranslationsTasks';\n\ntype TranslateDictionaryResult = TranslationTask & {\n dictionaryOutput: Dictionary | null;\n};\n\ntype TranslateDictionaryOptions = {\n mode: 'complete' | 'review';\n aiOptions?: AIOptions;\n fillMetadata?: boolean;\n onHandle?: ReturnType<\n typeof import('@intlayer/chokidar/utils').getGlobalLimiter\n >;\n onSuccess?: () => void;\n onError?: (error: unknown) => void;\n getAbortError?: () => Error | null;\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n};\n\nconst hasMissingMetadata = (dictionary: Dictionary) =>\n !dictionary.description || !dictionary.title || !dictionary.tags;\n\n/**\n * Recursively strips null values from an object, returning the cleaned content\n * and a separate object containing only the null-valued paths so they can be\n * re-injected after AI translation (nulls don't need translation).\n */\nconst stripNullValues = (\n obj: any\n): { content: any; nulls: any; hasNulls: boolean } => {\n if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {\n return { content: obj, nulls: undefined, hasNulls: false };\n }\n\n const content: any = {};\n const nulls: any = {};\n let hasNulls = false;\n\n for (const [key, value] of Object.entries(obj)) {\n if (value === null) {\n nulls[key] = null;\n hasNulls = true;\n } else {\n const child = stripNullValues(value);\n content[key] = child.content;\n if (child.hasNulls) {\n nulls[key] = child.nulls;\n hasNulls = true;\n }\n }\n }\n\n return { content, nulls: hasNulls ? nulls : undefined, hasNulls };\n};\n\nconst CHUNK_SIZE = 7000; // GPT-5 Mini safe input size\nconst GROUP_MAX_RETRY = 2;\nconst MAX_RETRY = 3;\nconst RETRY_DELAY = 1000 * 10; // 10 seconds\n\nconst MAX_FOLLOWING_ERRORS = 10; // 10 errors in a row, hard exit the process\nlet followingErrors = 0;\n\nexport const translateDictionary = async (\n task: TranslationTask,\n configuration: IntlayerConfig,\n options?: TranslateDictionaryOptions\n): Promise<TranslateDictionaryResult> => {\n const appLogger = getAppLogger(configuration);\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n const { mode, aiOptions, fillMetadata, aiClient, aiConfig } = {\n mode: 'complete',\n fillMetadata: true,\n ...options,\n } as const;\n\n const notifySuccess = () => {\n followingErrors = 0;\n options?.onSuccess?.();\n };\n\n const result = await retryManager(\n async () => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n\n const baseUnmergedDictionary: Dictionary | undefined =\n unmergedDictionariesRecord[task.dictionaryKey].find(\n (dict) => dict.localId === task.dictionaryLocalId\n );\n\n if (!baseUnmergedDictionary) {\n appLogger(\n `${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`,\n {\n level: 'warn',\n }\n );\n return { ...task, dictionaryOutput: null };\n }\n\n let metadata:\n | Pick<Dictionary, 'description' | 'title' | 'tags'>\n | undefined;\n\n if (\n fillMetadata &&\n (hasMissingMetadata(baseUnmergedDictionary) || mode === 'review')\n ) {\n const defaultLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n configuration.internationalization.defaultLocale\n );\n\n appLogger(\n `${task.dictionaryPreset} Filling missing metadata for ${colorizePath(basename(baseUnmergedDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const runAudit = async () => {\n if (aiClient && aiConfig) {\n const result = await aiClient.auditDictionaryMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiConfig,\n });\n\n return {\n data: result,\n };\n }\n\n return await intlayerAPI.ai.auditContentDeclarationMetadata({\n fileContent: JSON.stringify(defaultLocaleDictionary),\n aiOptions,\n });\n };\n\n const metadataResult = options?.onHandle\n ? await options.onHandle(runAudit)\n : await runAudit();\n\n metadata = metadataResult.data?.fileContent;\n }\n\n const translatedContentResults = await Promise.all(\n task.targetLocales.map(async (targetLocale) => {\n /**\n * In complete mode, for large dictionaries, we want to filter all content that is already translated\n *\n * targetLocale: fr\n *\n * { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}\n * { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }\n *\n */\n // Reset to base dictionary for each locale to ensure we filter from the original\n let dictionaryToProcess = structuredClone(baseUnmergedDictionary);\n\n let targetLocaleDictionary: Dictionary;\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // For per-locale files, the content is already in simple JSON format (not translation nodes)\n // The base dictionary is already the source locale content\n\n // Load the existing target locale dictionary\n const targetLocaleFilePath =\n baseUnmergedDictionary.filePath?.replace(\n new RegExp(`/${task.sourceLocale}/`, 'g'),\n `/${targetLocale}/`\n );\n\n // Find the target locale dictionary in unmerged dictionaries\n const targetUnmergedDictionary = targetLocaleFilePath\n ? unmergedDictionariesRecord[task.dictionaryKey]?.find(\n (dict) =>\n dict.filePath === targetLocaleFilePath &&\n dict.locale === targetLocale\n )\n : undefined;\n\n targetLocaleDictionary = targetUnmergedDictionary ?? {\n key: baseUnmergedDictionary.key,\n content: {},\n filePath: targetLocaleFilePath,\n locale: targetLocale,\n };\n\n // In complete mode, filter out already translated content\n if (mode === 'complete') {\n dictionaryToProcess = getFilterMissingContentPerLocale(\n dictionaryToProcess,\n targetUnmergedDictionary\n );\n }\n } else {\n // For multilingual dictionaries\n if (mode === 'complete') {\n // Remove all nodes that don't have any content to translate\n dictionaryToProcess = getFilterMissingTranslationsDictionary(\n dictionaryToProcess,\n targetLocale\n );\n }\n\n dictionaryToProcess = getPerLocaleDictionary(\n dictionaryToProcess,\n task.sourceLocale\n );\n\n targetLocaleDictionary = getPerLocaleDictionary(\n baseUnmergedDictionary,\n targetLocale\n );\n }\n\n const localePreset = colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n formatLocale(targetLocale),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 18 }\n );\n\n const createChunkPreset = (\n chunkIndex: number,\n totalChunks: number\n ) => {\n if (totalChunks <= 1) return '';\n return colon(\n [\n colorize('[', ANSIColors.GREY_DARK),\n colorizeNumber(chunkIndex + 1),\n colorize(`/${totalChunks}`, ANSIColors.GREY_DARK),\n colorize(']', ANSIColors.GREY_DARK),\n ].join(''),\n { colSize: 5 }\n );\n };\n\n appLogger(\n `${task.dictionaryPreset}${localePreset} Preparing ${colorizePath(basename(targetLocaleDictionary.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n const isContentStructured =\n (typeof dictionaryToProcess.content === 'object' &&\n dictionaryToProcess.content !== null) ||\n Array.isArray(dictionaryToProcess.content);\n\n const rawContentToProcess = isContentStructured\n ? dictionaryToProcess.content\n : {\n __INTLAYER_ROOT_PRIMITIVE_CONTENT__:\n dictionaryToProcess.content,\n };\n\n // Strip null values before sending to AI — nulls need no translation\n // and confuse the model. They will be re-injected after merging.\n const { content: contentToProcess, nulls: strippedNullValues } =\n stripNullValues(rawContentToProcess);\n\n const chunkedJsonContent: JsonChunk[] = chunkJSON(\n contentToProcess as unknown as Record<string, any>,\n CHUNK_SIZE\n );\n\n const nbOfChunks = chunkedJsonContent.length;\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset} Split into ${colorizeNumber(nbOfChunks)} chunks for translation`,\n {\n level: 'info',\n }\n );\n }\n\n const chunkResult: JsonChunk[] = [];\n\n // Process chunks in parallel (globally throttled) to allow concurrent translation\n const chunkPromises = chunkedJsonContent.map((chunk) => {\n const chunkPreset = createChunkPreset(chunk.index, chunk.total);\n\n if (nbOfChunks > 1) {\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`,\n {\n level: 'info',\n }\n );\n }\n\n // Reconstruct partial JSON content from this chunk's patches\n const chunkContent = reconstructFromSingleChunk(chunk);\n const presetOutputContent = reduceObjectFormat(\n isContentStructured\n ? targetLocaleDictionary.content\n : {\n __INTLAYER_ROOT_PRIMITIVE_CONTENT__:\n targetLocaleDictionary.content,\n },\n chunkContent\n ) as unknown as JSON;\n\n const executeTranslation = async () => {\n return await retryManager(\n async () => {\n let translationResult: any;\n\n if (aiClient && aiConfig) {\n translationResult = await aiClient.translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiConfig,\n });\n } else {\n translationResult = await intlayerAPI.ai\n .translateJSON({\n entryFileContent: chunkContent as unknown as JSON,\n presetOutputContent,\n dictionaryDescription:\n dictionaryToProcess.description ??\n metadata?.description ??\n '',\n entryLocale: task.sourceLocale,\n outputLocale: targetLocale,\n mode,\n aiOptions,\n })\n .then((result) => result.data);\n }\n\n if (!translationResult?.fileContent) {\n throw new Error('No content result');\n }\n\n const { isIdentic } = verifyIdenticObjectFormat(\n translationResult.fileContent,\n chunkContent\n );\n\n if (!isIdentic) {\n throw new Error(\n 'Translation result does not match expected format'\n );\n }\n\n notifySuccess();\n return translationResult.fileContent;\n },\n {\n maxRetry: MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) => {\n const chunkPreset = createChunkPreset(\n chunk.index,\n chunk.total\n );\n appLogger(\n `${task.dictionaryPreset}${localePreset}${chunkPreset} ${colorize('Error filling:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n );\n\n followingErrors += 1;\n\n if (followingErrors >= MAX_FOLLOWING_ERRORS) {\n appLogger(`There is something wrong.`, {\n level: 'error',\n });\n process.exit(1); // 1 for error\n }\n },\n }\n )();\n };\n\n const wrapped = options?.onHandle\n ? options.onHandle(executeTranslation) // queued in global limiter\n : executeTranslation(); // no global limiter\n\n return wrapped.then((result) => ({ chunk, result }));\n });\n\n // Wait for all chunks for this locale in parallel (still capped by global limiter)\n const chunkResults = await Promise.all(chunkPromises);\n\n // Maintain order\n chunkResults\n .sort((chunkA, chunkB) => chunkA.chunk.index - chunkB.chunk.index)\n .forEach(({ result }) => {\n chunkResult.push(result);\n });\n\n // Merge partial JSON objects produced from each chunk into a single object\n let mergedContent = mergeChunks(chunkResult);\n\n // Re-inject null values that were stripped before AI translation\n if (strippedNullValues) {\n mergedContent = deepMergeContent(mergedContent, strippedNullValues);\n }\n\n const merged = {\n ...dictionaryToProcess,\n content: mergedContent,\n };\n\n // For per-locale files, merge the newly translated content with existing target content\n let finalContent = merged.content;\n\n if (!isContentStructured) {\n finalContent = (finalContent as any)\n ?.__INTLAYER_ROOT_PRIMITIVE_CONTENT__;\n }\n\n if (typeof baseUnmergedDictionary.locale === 'string') {\n // Deep merge: existing content + newly translated content\n finalContent = deepMergeContent(\n targetLocaleDictionary.content ?? {},\n finalContent\n );\n }\n\n return [targetLocale, finalContent] as const;\n })\n );\n\n const translatedContent: Partial<Record<Locale, Dictionary['content']>> =\n Object.fromEntries(translatedContentResults);\n\n const baseDictionary = baseUnmergedDictionary.locale\n ? {\n ...baseUnmergedDictionary,\n key: baseUnmergedDictionary.key!,\n content: {},\n }\n : baseUnmergedDictionary;\n\n let dictionaryOutput: Dictionary = {\n ...getMultilingualDictionary(baseDictionary),\n locale: undefined, // Ensure the dictionary is multilingual\n ...metadata,\n };\n\n for (const targetLocale of task.targetLocales) {\n if (translatedContent[targetLocale]) {\n dictionaryOutput = insertContentInDictionary(\n dictionaryOutput,\n translatedContent[targetLocale],\n targetLocale\n );\n }\n }\n\n appLogger(\n `${task.dictionaryPreset} ${colorize('Translation completed successfully', ANSIColors.GREEN)} for ${colorizePath(basename(dictionaryOutput.filePath!))}`,\n {\n level: 'info',\n }\n );\n\n // The dict-level `fill` value may have been lost during JSON serialisation\n // (functions can't be serialised to JSON). Fall back to the config-level\n // fill so that an explicit fill in intlayer.config.ts is honoured.\n const effectiveFillForCheck =\n baseUnmergedDictionary.fill ?? configuration.dictionary?.fill;\n\n if (\n baseUnmergedDictionary.locale &&\n (effectiveFillForCheck === true ||\n effectiveFillForCheck === undefined) &&\n baseUnmergedDictionary.location === 'local'\n ) {\n const dictionaryFilePath = baseUnmergedDictionary\n .filePath!.split('.')\n .slice(0, -1);\n\n const contentIndex = dictionaryFilePath[dictionaryFilePath.length - 1];\n\n return JSON.parse(\n JSON.stringify({\n ...task,\n dictionaryOutput: {\n ...dictionaryOutput,\n fill: undefined,\n filled: true,\n },\n }).replaceAll(\n new RegExp(`\\\\.${contentIndex}\\\\.[a-zA-Z0-9]+`, 'g'),\n `.filled.${contentIndex}.json`\n )\n );\n }\n\n return {\n ...task,\n dictionaryOutput,\n };\n },\n {\n maxRetry: GROUP_MAX_RETRY,\n delay: RETRY_DELAY,\n onError: ({ error, attempt, maxRetry }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Error:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)} - Attempt ${colorizeNumber(attempt + 1)} of ${colorizeNumber(maxRetry)}`,\n {\n level: 'error',\n }\n ),\n onMaxTryReached: ({ error }) =>\n appLogger(\n `${task.dictionaryPreset} ${colorize('Maximum number of retries reached:', ANSIColors.RED)} ${colorize(typeof error === 'string' ? error : JSON.stringify(error), ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n ),\n }\n )();\n\n return result as TranslateDictionaryResult;\n};\n"],"mappings":";;;;;;;;;;;;AAsDA,MAAM,sBAAsB,eAC1B,CAAC,WAAW,eAAe,CAAC,WAAW,SAAS,CAAC,WAAW;;;;;;AAO9D,MAAM,mBACJ,QACoD;AACpD,KAAI,OAAO,QAAQ,YAAY,QAAQ,QAAQ,MAAM,QAAQ,IAAI,CAC/D,QAAO;EAAE,SAAS;EAAK,OAAO;EAAW,UAAU;EAAO;CAG5D,MAAM,UAAe,EAAE;CACvB,MAAM,QAAa,EAAE;CACrB,IAAI,WAAW;AAEf,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,CAC5C,KAAI,UAAU,MAAM;AAClB,QAAM,OAAO;AACb,aAAW;QACN;EACL,MAAM,QAAQ,gBAAgB,MAAM;AACpC,UAAQ,OAAO,MAAM;AACrB,MAAI,MAAM,UAAU;AAClB,SAAM,OAAO,MAAM;AACnB,cAAW;;;AAKjB,QAAO;EAAE;EAAS,OAAO,WAAW,QAAQ;EAAW;EAAU;;AAGnE,MAAM,aAAa;AACnB,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,c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G,KAAK,iBAAiB,GAAG,SAAS,sCAAsC,WAAW,MAAM,CAAC,OAAO,aAAa,SAAS,iBAAiB,SAAU,CAAC,IACtJ,EACE,OAAO,QACR,CACF;EAKD,MAAM,wBACJ,uBAAuB,QAAQ,cAAc,YAAY;AAE3D,MACE,uBAAuB,WACtB,0BAA0B,QACzB,0BAA0B,WAC5B,uBAAuB,aAAa,SACpC;GACA,MAAM,qBAAqB,uBACxB,SAAU,MAAM,IAAI,CACpB,MAAM,GAAG,GAAG;GAEf,MAAM,eAAe,mBAAmB,mBAAmB,SAAS;AAEpE,UAAO,KAAK,MACV,KAAK,UAAU;IACb,GAAG;IACH,kBAAkB;KAChB,GAAG;KACH,MAAM;KACN,QAAQ;KACT;IACF,CAAC,CAAC,WACD,IAAI,OAAO,MAAM,aAAa,kBAAkB,IAAI,EACpD,WAAW,aAAa,OACzB,CACF;;AAGH,SAAO;GACL,GAAG;GACH;GACD;IAEH;EACE,UAAU;EACV,OAAO;EACP,UAAU,EAAE,OAAO,SAAS,eAC1B,UACE,GAAG,KAAK,iBAAiB,GAAG,SAAS,UAAU,WAAW,IAAI,CAAC,GAAG,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,CAAC,aAAa,eAAe,UAAU,EAAE,CAAC,MAAM,eAAe,SAAS,IACnO,EACE,OAAO,SACR,CACF;EACH,kBAAkB,EAAE,YAClB,UACE,GAAG,KAAK,iBAAiB,GAAG,SAAS,sCAAsC,WAAW,IAAI,CAAC,GAAG,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,MAAM,EAAE,WAAW,UAAU,IACvL,EACE,OAAO,SACR,CACF;EACJ,CACF,EAAE"}
@@ -41,11 +41,9 @@ const writeFill = async (contentDeclarationFile, outputLocales, parentLocales, c
41
41
  locale: output.isPerLocale ? output.localeList[0] : void 0,
42
42
  localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,
43
43
  filePath: relativeFilePath
44
- }, configuration, { localeList: output.localeList });
45
- if (output.isPerLocale) {
46
- const sourceLocale = output.localeList[0];
47
- appLogger(`Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`, { level: "info" });
48
- } else appLogger(`Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`, { level: "info" });
44
+ }, configuration, { localeList: output.isPerLocale ? output.localeList : outputLocales ?? configuration.internationalization.locales });
45
+ if (output.isPerLocale) appLogger(`Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(output.localeList[0])}`, { level: "info" });
46
+ else appLogger(`Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`, { level: "info" });
49
47
  }
50
48
  };
51
49
 
@@ -1 +1 @@
1
- {"version":3,"file":"writeFill.mjs","names":[],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { writeContentDeclaration } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, Fill } from '@intlayer/types/dictionary';\nimport { type FillData, formatFillData } from './formatFillData';\nimport { getAvailableLocalesInDictionary } from './getAvailableLocalesInDictionary';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const requestedLocales: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n // Get locales that actually have translations in the content\n const availableLocales = getAvailableLocalesInDictionary(\n contentDeclarationFile\n );\n\n // Only write files for locales that have actual translations\n const localeList = requestedLocales.filter((locale) =>\n availableLocales.includes(locale)\n );\n\n if (localeList.length === 0) {\n appLogger(\n `No translations available for dictionary '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const fillData: FillData[] = await formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.system.baseDir,\n output.filePath\n );\n\n // write file\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n localeList: output.localeList,\n }\n );\n\n if (output.isPerLocale) {\n const sourceLocale = output.localeList[0];\n\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(sourceLocale)}`,\n {\n level: 'info',\n }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n {\n level: 'info',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAWA,MAAa,YAAY,OACvB,wBACA,eACA,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S,CAAC,cAAc,aAAa,aAAa,IACtK,EACE,OAAO,QACR,CACF;QAED,WACE,wCAAwC,YAAY,eAAe,IAAI,CAAC,eAAe,WAAW,OAAO,SAAS,IAClH,EACE,OAAO,QACR,CACF"}
1
+ {"version":3,"file":"writeFill.mjs","names":[],"sources":["../../../src/fill/writeFill.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { writeContentDeclaration } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary, Fill } from '@intlayer/types/dictionary';\nimport { type FillData, formatFillData } from './formatFillData';\nimport { getAvailableLocalesInDictionary } from './getAvailableLocalesInDictionary';\n\nexport const writeFill = async (\n contentDeclarationFile: Dictionary,\n outputLocales: Locale[],\n parentLocales: Locale[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n const dictionaries = getDictionaries(configuration);\n\n const fullDictionary = dictionaries[contentDeclarationFile.key];\n\n const { filePath } = contentDeclarationFile;\n\n if (!filePath) {\n appLogger('No file path found for dictionary', {\n level: 'error',\n });\n return;\n }\n\n const fillOptions: Fill | undefined =\n contentDeclarationFile.fill ?? configuration.dictionary?.fill ?? true;\n\n if ((fillOptions as boolean) === false) {\n appLogger(\n `Auto fill is disabled for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const requestedLocales: Locale[] = (\n outputLocales ?? configuration.internationalization.locales\n ).filter((locale) => !parentLocales?.includes(locale));\n\n // Get locales that actually have translations in the content\n const availableLocales = getAvailableLocalesInDictionary(\n contentDeclarationFile\n );\n\n // Only write files for locales that have actual translations\n const localeList = requestedLocales.filter((locale) =>\n availableLocales.includes(locale)\n );\n\n if (localeList.length === 0) {\n appLogger(\n `No translations available for dictionary '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'info',\n }\n );\n return;\n }\n\n const fillData: FillData[] = await formatFillData(\n fillOptions as Fill,\n localeList,\n filePath,\n fullDictionary.key,\n configuration\n );\n\n for await (const output of fillData) {\n if (!output.filePath) {\n appLogger(\n `No file path found for auto filled content declaration for '${colorizeKey(fullDictionary.key)}'`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n const { fill, ...rest } = contentDeclarationFile;\n\n const relativeFilePath = relative(\n configuration.system.baseDir,\n output.filePath\n );\n\n await writeContentDeclaration(\n {\n ...rest,\n filled: true,\n locale: output.isPerLocale ? output.localeList[0] : undefined,\n localId: `${contentDeclarationFile.key}::local::${relativeFilePath}`,\n filePath: relativeFilePath,\n },\n configuration,\n {\n // Per-locale files: write only the specific locale.\n // Multilingual files (string/function fill, single output): include all\n // output locales (including source) so the file is complete.\n localeList: output.isPerLocale\n ? output.localeList\n : (outputLocales ?? configuration.internationalization.locales),\n }\n );\n\n if (output.isPerLocale) {\n appLogger(\n `Auto filled per-locale content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)} for locale ${formatLocale(output.localeList[0])}`,\n { level: 'info' }\n );\n } else {\n appLogger(\n `Auto filled content declaration for '${colorizeKey(fullDictionary.key)}' written to ${formatPath(output.filePath)}`,\n { level: 'info' }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAWA,MAAa,YAAY,OACvB,wBACA,eACA,eACA,kBACG;CACH,MAAM,YAAY,aAAa,cAAc;CAG7C,MAAM,iBAFe,gBAAgB,cAAc,CAEf,uBAAuB;CAE3D,MAAM,EAAE,aAAa;AAErB,KAAI,CAAC,UAAU;AACb,YAAU,qCAAqC,EAC7C,OAAO,SACR,CAAC;AACF;;CAGF,MAAM,cACJ,uBAAuB,QAAQ,cAAc,YAAY,QAAQ;AAEnE,KAAK,gBAA4B,OAAO;AACtC,YACE,8BAA8B,YAAY,eAAe,IAAI,CAAC,IAC9D,EACE,OAAO,QACR,CACF;AACD;;CAGF,MAAM,oBACJ,iBAAiB,cAAc,qBAAqB,SACpD,QAAQ,WAAW,CAAC,eAAe,SAAS,OAAO,CAAC;CAGtD,MAAM,mBAAmB,gCACvB,uBACD;CAGD,MAAM,aAAa,iBAAiB,QAAQ,WAC1C,iBAAiB,SAAS,OAAO,CAClC;AAED,KAAI,WAAW,WAAW,GAAG;AAC3B,YACE,6CAA6C,YAAY,eAAe,IAAI,CAAC,IAC7E,EACE,OAAO,QACR,CACF;AACD;;CAGF,MAAM,WAAuB,MAAM,eACjC,aACA,YACA,UACA,eAAe,KACf,cACD;AAED,YAAW,MAAM,UAAU,UAAU;AACnC,MAAI,CAAC,OAAO,UAAU;AACpB,aACE,+DAA+D,YAAY,eAAe,IAAI,CAAC,IAC/F,EACE,OAAO,SACR,CACF;AACD;;EAGF,MAAM,EAAE,MAAM,GAAG,SAAS;EAE1B,MAAM,mBAAmB,SACvB,cAAc,OAAO,SACrB,OAAO,SACR;AAED,QAAM,wBACJ;GACE,GAAG;GACH,QAAQ;GACR,QAAQ,OAAO,cAAc,OAAO,WAAW,KAAK;GACpD,SAAS,GAAG,uBAAuB,IAAI,WAAW;GAClD,UAAU;GACX,EACD,eACA,EAIE,YAAY,OAAO,cACf,OAAO,aACN,iBAAiB,cAAc,qBAAqB,SAC1D,CACF;AAED,MAAI,OAAO,YACT,WACE,mDAAmD,YAAY,eAAe,IAAI,CAAC,eAAe,WAAW,OAAO,SAAS,CAAC,cAAc,aAAa,OAAO,WAAW,GAAG,IAC9K,EAAE,OAAO,QAAQ,CAClB;MAED,WACE,wCAAwC,YAAY,eAAe,IAAI,CAAC,eAAe,WAAW,OAAO,SAAS,IAClH,EAAE,OAAO,QAAQ,CAClB"}
@@ -1,6 +1,6 @@
1
1
  import { setupAI } from "../utils/setupAI.mjs";
2
- import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
3
2
  import { getOutputFilePath } from "../utils/getOutputFilePath.mjs";
3
+ import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
4
4
  import { reviewFileBlockAware } from "./reviewDocBlockAware.mjs";
5
5
  import { existsSync } from "node:fs";
6
6
  import { join, relative } from "node:path";
@@ -10,9 +10,9 @@ const listMissingTranslationsWithConfig = (configuration) => {
10
10
  const mergedDictionaries = getDictionaries(configuration);
11
11
  const missingTranslations = [];
12
12
  const { locales, requiredLocales } = configuration.internationalization;
13
- const dictionariesKeys = Object.keys(unmergedDictionariesRecord);
13
+ const dictionariesKeys = new Set([...Object.keys(unmergedDictionariesRecord), ...Object.keys(mergedDictionaries)]);
14
14
  for (const dictionaryKey of dictionariesKeys) {
15
- const dictionaries = unmergedDictionariesRecord[dictionaryKey];
15
+ const dictionaries = unmergedDictionariesRecord[dictionaryKey] ?? [];
16
16
  const multilingualDictionary = dictionaries.filter((dictionary) => !dictionary.locale);
17
17
  for (const dictionary of multilingualDictionary) {
18
18
  const missingLocales = getMissingLocalesContentFromDictionary(dictionary, locales);
@@ -23,7 +23,21 @@ const listMissingTranslationsWithConfig = (configuration) => {
23
23
  locales: missingLocales
24
24
  });
25
25
  }
26
- if (dictionaries.filter((dictionary) => dictionary.locale).length === 0) continue;
26
+ const perLocaleDictionary = dictionaries.filter((dictionary) => dictionary.locale);
27
+ if (dictionaries.length === 0) {
28
+ const mergedDictionary = mergedDictionaries[dictionaryKey];
29
+ if (mergedDictionary) {
30
+ const missingLocales = getMissingLocalesContentFromDictionary(mergedDictionary, locales);
31
+ if (missingLocales.length > 0) missingTranslations.push({
32
+ key: dictionaryKey,
33
+ id: mergedDictionary.id,
34
+ filePath: mergedDictionary.filePath,
35
+ locales: missingLocales
36
+ });
37
+ }
38
+ continue;
39
+ }
40
+ if (perLocaleDictionary.length === 0) continue;
27
41
  const mergedDictionary = mergedDictionaries[dictionaryKey];
28
42
  const missingLocales = getMissingLocalesContentFromDictionary(mergedDictionary, locales);
29
43
  if (missingLocales.length > 0) missingTranslations.push({
@@ -31,7 +45,7 @@ const listMissingTranslationsWithConfig = (configuration) => {
31
45
  locales: missingLocales
32
46
  });
33
47
  }
34
- const missingLocalesSet = new Set(missingTranslations.flatMap((t) => t.locales));
48
+ const missingLocalesSet = new Set(missingTranslations.flatMap((missingTranslation) => missingTranslation.locales));
35
49
  const missingLocales = Array.from(missingLocalesSet);
36
50
  return {
37
51
  missingTranslations,
@@ -1 +1 @@
1
- {"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n const dictionariesKeys = Object.keys(unmergedDictionariesRecord);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap((t) => t.locales)\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":";;;;;;;AAYA,MAAa,qCACX,kBACG;CACH,MAAM,6BAA6B,wBAAwB,cAAc;CACzE,MAAM,qBAAqB,gBAAgB,cAAc;CAEzD,MAAM,sBAKA,EAAE;CAER,MAAM,EAAE,SAAS,oBAAoB,cAAc;CAEnD,MAAM,mBAAmB,OAAO,KAAK,2BAA2B;AAEhE,MAAK,MAAM,iBAAiB,kBAAkB;EAC5C,MAAM,eACJ,2BAA2B;EAE7B,MAAM,yBAAuC,aAAa,QACvD,eAAe,CAAC,WAAW,OAC7B;AAGD,OAAK,MAAM,cAAc,wBAAwB;GAC/C,MAAM,iBAAiB,uCACrB,YACA,QACD;AAED,OAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;IACvB,KAAK;IACL,IAAI,WAAW;IACf,UAAU,WAAW;IACrB,SAAS;IACV,CAAC;;AAQN,MAJ0C,aAAa,QACpD,eAAe,WAAW,OAC5B,CAEuB,WAAW,EACjC;EAGF,MAAM,mBAAmB,mBAAmB;EAE5C,MAAM,iBAAiB,uCACrB,kBACA,QACD;AAED,MAAI,eAAe,SAAS,EAC1B,qBAAoB,KAAK;GACvB,KAAK;GACL,SAAS;GACV,CAAC;;CAIN,MAAM,oBAAoB,IAAI,IAC5B,oBAAoB,SAAS,MAAM,EAAE,QAAQ,CAC9C;CACD,MAAM,iBAAiB,MAAM,KAAK,kBAAkB;AAMpD,QAAO;EAAE;EAAqB;EAAgB,wBAJf,eAAe,QAAQ,YACnD,mBAAmB,SAAS,SAAS,OAAO,CAC9C;EAEqE;;AAGxE,MAAa,2BACX,yBACG;CACH,MAAM,gBAAgB,iBAAiB,qBAAqB;AAC5D,kBAAiB,qBAAqB;AAEtC,QAAO,kCAAkC,cAAc"}
1
+ {"version":3,"file":"listMissingTranslations.mjs","names":[],"sources":["../../../src/test/listMissingTranslations.ts"],"sourcesContent":["import { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getMissingLocalesContentFromDictionary } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\nexport const listMissingTranslationsWithConfig = (\n configuration: IntlayerConfig\n) => {\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const mergedDictionaries = getDictionaries(configuration);\n\n const missingTranslations: {\n key: string;\n filePath?: string;\n id?: string;\n locales: Locale[];\n }[] = [];\n\n const { locales, requiredLocales } = configuration.internationalization;\n\n // Use the union of keys from both unmerged and merged dictionaries so that\n // dictionaries compiled only as merged (no per-locale split) are still checked.\n const dictionariesKeys = new Set([\n ...Object.keys(unmergedDictionariesRecord),\n ...Object.keys(mergedDictionaries),\n ]);\n\n for (const dictionaryKey of dictionariesKeys) {\n const dictionaries: Dictionary[] =\n unmergedDictionariesRecord[dictionaryKey] ?? [];\n\n const multilingualDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => !dictionary.locale\n );\n\n // Test all by merging all dictionaries to ensure no per-locale dictionary is missing\n for (const dictionary of multilingualDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n dictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: dictionary.id,\n filePath: dictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n const perLocaleDictionary: Dictionary[] = dictionaries.filter(\n (dictionary) => dictionary.locale\n );\n\n // If there are no unmerged dictionaries for this key, fall back to the\n // merged dictionary directly (covers the case where the dict was compiled\n // as merged-only and unmerged_dictionaries.cjs is empty for this key).\n if (dictionaries.length === 0) {\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n if (mergedDictionary) {\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n id: mergedDictionary.id,\n filePath: mergedDictionary.filePath,\n locales: missingLocales,\n });\n }\n }\n\n continue;\n }\n\n if (perLocaleDictionary.length === 0) {\n continue;\n }\n\n const mergedDictionary = mergedDictionaries[dictionaryKey];\n\n const missingLocales = getMissingLocalesContentFromDictionary(\n mergedDictionary,\n locales\n );\n\n if (missingLocales.length > 0) {\n missingTranslations.push({\n key: dictionaryKey,\n locales: missingLocales,\n });\n }\n }\n\n const missingLocalesSet = new Set(\n missingTranslations.flatMap(\n (missingTranslation) => missingTranslation.locales\n )\n );\n const missingLocales = Array.from(missingLocalesSet);\n\n const missingRequiredLocales = missingLocales.filter((locale) =>\n (requiredLocales ?? locales).includes(locale)\n );\n\n return { missingTranslations, missingLocales, missingRequiredLocales };\n};\n\nexport const listMissingTranslations = (\n configurationOptions?: GetConfigurationOptions\n) => {\n const configuration = getConfiguration(configurationOptions);\n logConfigDetails(configurationOptions);\n\n return listMissingTranslationsWithConfig(configuration);\n};\n"],"mappings":";;;;;;;AAYA,MAAa,qCACX,kBAC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B,SAAS,SAAS,OAAO,CAC9C;EAEqE;;AAGxE,MAAa,2BACX,yBACG;CACH,MAAM,gBAAgB,iBAAiB,qBAAqB;AAC5D,kBAAiB,qBAAqB;AAEtC,QAAO,kCAAkC,cAAc"}
@@ -1,6 +1,6 @@
1
1
  import { setupAI } from "../utils/setupAI.mjs";
2
- import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
3
2
  import { getOutputFilePath } from "../utils/getOutputFilePath.mjs";
3
+ import { checkFileModifiedRange } from "../utils/checkFileModifiedRange.mjs";
4
4
  import { translateFile } from "./translateFile.mjs";
5
5
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";