@babelize/engine 0.3.7 → 0.3.9

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 (50) hide show
  1. package/dist/analysis/analyze.d.ts +3 -0
  2. package/dist/analysis/analyze.js +1 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +16 -1
  5. package/dist/local/hosted-provider.js +1 -0
  6. package/dist/local/translate-core.d.ts +19 -2
  7. package/dist/local/translate-core.js +28 -9
  8. package/dist/local/translate-messages.d.ts +5 -0
  9. package/dist/local/translate-messages.js +1 -1
  10. package/dist/modules/extractor/extract.js +22 -5
  11. package/dist/modules/finalization/finalize.d.ts +6 -0
  12. package/dist/modules/finalization/finalize.js +25 -5
  13. package/dist/modules/finalization/nextjs-finalize.d.ts +63 -6
  14. package/dist/modules/finalization/nextjs-finalize.js +339 -26
  15. package/dist/modules/format-injection/index.js +3 -2
  16. package/dist/modules/injection/inject.js +2 -1
  17. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  18. package/dist/modules/locale-builder/adopted.js +185 -16
  19. package/dist/modules/locale-builder/locales.js +11 -2
  20. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  21. package/dist/modules/locale-builder/message-modules.js +263 -0
  22. package/dist/modules/sync-detector/sync-detector.js +4 -1
  23. package/dist/modules/translator/client/byok.provider.js +8 -2
  24. package/dist/modules/translator/formality.d.ts +40 -0
  25. package/dist/modules/translator/formality.js +313 -0
  26. package/dist/modules/translator/translate.d.ts +18 -0
  27. package/dist/modules/translator/translate.js +78 -11
  28. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  29. package/dist/modules/workspace/existing-setup.js +32 -15
  30. package/dist/modules/workspace/validate.js +7 -0
  31. package/dist/orchestrator.js +51 -7
  32. package/dist/providers/default-translation-provider.js +2 -2
  33. package/dist/providers/types.d.ts +5 -0
  34. package/dist/qa/check-project.d.ts +7 -0
  35. package/dist/qa/check-project.js +12 -2
  36. package/dist/qa/locale-files.d.ts +8 -5
  37. package/dist/qa/locale-files.js +37 -9
  38. package/dist/qa/locale-qa.d.ts +10 -1
  39. package/dist/qa/locale-qa.js +9 -0
  40. package/dist/qa/review.js +1 -1
  41. package/dist/runtime/types.d.ts +29 -1
  42. package/dist/types.d.ts +2 -0
  43. package/dist/utils/ast-helpers.js +35 -4
  44. package/dist/utils/source-scope.d.ts +30 -0
  45. package/dist/utils/source-scope.js +112 -0
  46. package/dist/utils/translator-caller.d.ts +19 -0
  47. package/dist/utils/translator-caller.js +55 -21
  48. package/dist/utils/ui-copy.d.ts +14 -0
  49. package/dist/utils/ui-copy.js +51 -0
  50. package/package.json +4 -2
@@ -42,6 +42,7 @@ const fast_glob_1 = __importDefault(require("fast-glob"));
42
42
  const i18n_1 = require("../../detection/i18n");
43
43
  const locale_files_1 = require("../../qa/locale-files");
44
44
  const file_utils_1 = require("../../utils/file-utils");
45
+ const message_modules_1 = require("../locale-builder/message-modules");
45
46
  /**
46
47
  * An app that already ships its own i18n setup — vue-i18n with
47
48
  * frontend/locales/, next-intl with messages/, react-i18next with
@@ -52,7 +53,9 @@ const file_utils_1 = require("../../utils/file-utils");
52
53
  * Returns null when there is nothing to adopt: no i18n library, no locale
53
54
  * files, or the files are where Babelize writes them (`defaultLocaleDir`,
54
55
  * i.e. a setup Babelize generated). Throws, with what to do, when the app
55
- * has a setup whose files can't be used as they are.
56
+ * has a setup whose files can't be used as they are. Flat `<locale>.json`
57
+ * files, a folder per locale of JSON namespaces and TypeScript/JS message
58
+ * modules are adopted (#370).
56
59
  */
57
60
  async function detectExistingSetup(opts) {
58
61
  const deps = Object.keys({ ...opts.packageJson?.dependencies, ...opts.packageJson?.devDependencies });
@@ -63,32 +66,45 @@ async function detectExistingSetup(opts) {
63
66
  if (await (0, file_utils_1.pathExists)(path.join(opts.workspacePath, opts.defaultLocaleDir, `${opts.sourceLocale}.json`)))
64
67
  return null;
65
68
  const appRoot = path.join(opts.workspacePath, opts.appDir);
66
- const sets = await (0, locale_files_1.findLocaleFileSets)(appRoot);
69
+ const sets = await (0, locale_files_1.findLocaleFileSets)(appRoot, { modules: true });
67
70
  if (sets.length === 0)
68
71
  return null;
69
72
  const libraryName = i18n_1.I18N_LIBRARY_NAMES[library];
70
73
  const rel = (set) => toPosix(path.join(opts.appDir, set.dir));
71
74
  const withSource = sets.filter((s) => s.files[opts.sourceLocale]);
72
- const flat = withSource.filter((s) => s.layout === 'flat');
73
- if (flat.length === 0) {
74
- const nested = withSource.find((s) => s.layout === 'namespaced');
75
- if (nested) {
76
- throw new Error(`This project already uses ${libraryName} with namespaced locale files (${rel(nested)}/<locale>/<namespace>.json). ` +
77
- `Babelize translates flat locale files (<locale>.json) only, and won't set up a second i18n configuration next to yours. Nothing was changed.`);
78
- }
75
+ if (withSource.length === 0) {
79
76
  const biggest = sets.reduce((a, b) => (Object.keys(b.files).length > Object.keys(a.files).length ? b : a));
80
77
  const found = Object.keys(biggest.files).sort();
81
78
  throw new Error(`This project already uses ${libraryName} with locale files in ${rel(biggest)} (${found.join(', ')}), but none for the source language "${opts.sourceLocale}". ` +
82
79
  `Set the source language to the one your ${rel(biggest)} files are written in. Nothing was changed.`);
83
80
  }
84
- // Several candidates: the one with the most languages, then the shallowest.
85
- const best = flat.sort((a, b) => Object.keys(b.files).length - Object.keys(a.files).length || a.dir.split('/').length - b.dir.split('/').length)[0];
81
+ // Several candidates: the one with the most languages, then the shallowest,
82
+ // then flat files over a folder per locale.
83
+ const order = { flat: 0, namespaced: 1, modules: 2 };
84
+ const best = withSource.sort((a, b) => Object.keys(b.files).length - Object.keys(a.files).length ||
85
+ a.dir.split('/').length - b.dir.split('/').length ||
86
+ order[a.layout] - order[b.layout])[0];
86
87
  const locales = Object.keys(best.files).sort();
87
88
  const localeDir = rel(best);
88
- return {
89
- setup: { library, localeDir, languageLists: await findLanguageLists(appRoot, opts.appDir, locales, opts.sourceLocale) },
90
- locales,
89
+ const setup = {
90
+ library,
91
+ localeDir,
92
+ languageLists: await findLanguageLists(appRoot, opts.appDir, locales, opts.sourceLocale),
91
93
  };
94
+ if (best.layout !== 'flat') {
95
+ setup.layout = best.layout;
96
+ setup.namespaces = best.files[opts.sourceLocale].map((f) => path.posix.basename(f)).sort();
97
+ if (best.layout === 'modules') {
98
+ const sourceDir = path.join(appRoot, best.dir, opts.sourceLocale);
99
+ for (const ext of message_modules_1.MESSAGE_MODULE_EXTENSIONS) {
100
+ if (await (0, file_utils_1.pathExists)(path.join(sourceDir, `index${ext}`))) {
101
+ setup.indexFile = `index${ext}`;
102
+ break;
103
+ }
104
+ }
105
+ }
106
+ }
107
+ return { setup, locales };
92
108
  }
93
109
  const CODE_FILES = '**/*.{js,jsx,ts,tsx,mjs,cjs,vue}';
94
110
  const MAX_SCANNED_FILES = 3000;
@@ -104,7 +120,8 @@ async function findLanguageLists(appRoot, appDir, locales, sourceLocale) {
104
120
  return [];
105
121
  const files = await (0, fast_glob_1.default)(CODE_FILES, {
106
122
  cwd: appRoot,
107
- ignore: locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS.map((d) => `**/${d}/**`),
123
+ // Tests list languages too, but registering one there doesn't ship it.
124
+ ignore: [...locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS.map((d) => `**/${d}/**`), '**/*.{test,spec}.*', '**/*.stories.*'],
108
125
  onlyFiles: true,
109
126
  deep: 8,
110
127
  followSymbolicLinks: false,
@@ -49,6 +49,7 @@ const stack_1 = require("../../detection/stack");
49
49
  const django_finalize_1 = require("../finalization/django-finalize");
50
50
  const locale_names_1 = require("../../django/locale-names");
51
51
  const existing_setup_1 = require("./existing-setup");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  const PY_IGNORE = ['**/node_modules/**', '**/.venv/**', '**/venv/**', '**/site-packages/**', '**/.git/**'];
53
54
  /**
54
55
  * The Django project root (directory of the shallowest manage.py), relative
@@ -252,6 +253,11 @@ async function validateWorkspace(config) {
252
253
  }
253
254
  const babelizeDir = path.join(workspacePath, '.babelize');
254
255
  await (0, file_utils_1.ensureDir)(babelizeDir);
256
+ // The project's include/exclude (#378): a published library's components,
257
+ // its CLI or fixtures stay untouched while the app around them is localized.
258
+ const sourceScope = (0, source_scope_1.mergeSourceScope)(await (0, source_scope_1.readSourceScope)(workspacePath), config.sourceScope);
259
+ if ((0, source_scope_1.hasSourceScope)(sourceScope))
260
+ logger_1.engineLogger.info('Limiting the run to the configured source scope', { ...sourceScope });
255
261
  const workspace = {
256
262
  path: workspacePath,
257
263
  framework,
@@ -262,6 +268,7 @@ async function validateWorkspace(config) {
262
268
  publicDir,
263
269
  ...(appDir !== '.' ? { appDir } : {}),
264
270
  ...(frameworkConfig.excludedPatterns ? { excludedPatterns: frameworkConfig.excludedPatterns } : {}),
271
+ ...((0, source_scope_1.hasSourceScope)(sourceScope) ? { sourceScope } : {}),
265
272
  packageJson: (packageJson ?? {}),
266
273
  formatConfig: config.formatConfig,
267
274
  ...(framework === 'django' ? { djangoRoot: djangoRoot ?? '.' } : {}),
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.RunAbortedError = void 0;
37
37
  exports.runEngineV2 = runEngineV2;
38
38
  const fs = __importStar(require("fs-extra"));
39
+ const path = __importStar(require("path"));
39
40
  const logger_1 = require("./utils/logger");
40
41
  const types_1 = require("@babelize/types");
41
42
  const workspace_1 = require("./modules/workspace");
@@ -45,7 +46,7 @@ const keygen_1 = require("./modules/keygen");
45
46
  const locale_builder_1 = require("./modules/locale-builder");
46
47
  const adopted_1 = require("./modules/locale-builder/adopted");
47
48
  const translate_1 = require("./modules/translator/translate");
48
- const glossary_1 = require("./modules/glossary");
49
+ const formality_1 = require("./modules/translator/formality");
49
50
  const translator_caller_1 = require("./utils/translator-caller");
50
51
  const injection_1 = require("./modules/injection");
51
52
  const summary_1 = require("./modules/summary");
@@ -132,9 +133,18 @@ async function runEngineV2(config) {
132
133
  // The app's own i18n setup (#367): its locale files, as they are before
133
134
  // the run, are the source of truth. Other languages' files are the
134
135
  // project's and are never removed.
136
+ // Message modules also read the other languages': a new language's are written like theirs (#370).
135
137
  const adopted = workspace.existingSetup
136
- ? await (0, adopted_1.readAdoptedLocales)(workspace, [config.sourceLocale, ...config.targetLocales])
138
+ ? await (0, adopted_1.readAdoptedLocales)(workspace, [...new Set([
139
+ config.sourceLocale,
140
+ ...config.targetLocales,
141
+ ...(workspace.existingSetup.layout === 'modules' ? workspace.existingLocales : []),
142
+ ])])
137
143
  : null;
144
+ // Babelize's own JSON locale files from an earlier run, as they are before
145
+ // this one: a translation someone corrected by hand wins over the
146
+ // lockfile, as it does in an adopted setup and in .po files.
147
+ const ownLocaleFiles = !adopted && workspace.localeFormat === 'json' ? await (0, adopted_1.readAdoptedLocales)(workspace, config.targetLocales) : null;
138
148
  // Remove stale locale files from previous runs that are no longer in targetLocales.
139
149
  // git reset --hard only resets tracked files; generated locale files are untracked
140
150
  // and persist across runs, causing stale languages to appear in outputs.
@@ -200,6 +210,7 @@ async function runEngineV2(config) {
200
210
  // (key, locale) pairs left for the next run: the run's maxTranslations ran out.
201
211
  let skippedForBudget = 0;
202
212
  let keyUsage;
213
+ let formalityNotes = [];
203
214
  let translationMetadata = {};
204
215
  if (config.projectId) {
205
216
  config.onProgress?.('Checking lockfile for cached translations...', 'lockfile', 'running');
@@ -238,6 +249,8 @@ async function runEngineV2(config) {
238
249
  // Likewise the translations in an adopted setup's locale files.
239
250
  if (adopted)
240
251
  lockfile = (0, adopted_1.seedLockfileFromLocaleFiles)(lockfile, flatKeys, targetFiles(adopted, config.targetLocales));
252
+ else if (ownLocaleFiles)
253
+ lockfile = (0, adopted_1.seedLockfileFromLocaleFiles)(lockfile, flatKeys, ownLocaleFiles, { onlyOverRecorded: true });
241
254
  // Pseudo-localization (--provider pseudo) is not a translation: a real
242
255
  // run treats pseudo values in the lockfile as missing and translates them.
243
256
  // The glossary is loaded once, here: keys whose glossary rules changed
@@ -245,9 +258,13 @@ async function runEngineV2(config) {
245
258
  // If the rules failed to load, stored translations are kept as they are
246
259
  // rather than redone without the glossary.
247
260
  const rules = await (0, translate_1.loadProjectTranslationRules)(config.projectId, config.providers?.rules);
261
+ // An adopted setup's existing translations show the form of address the
262
+ // app uses; new ones follow it where none is configured (#371).
263
+ if (adopted)
264
+ formalityNotes = detectAdoptedFormality(rules, adopted, config.targetLocales);
248
265
  const lockfileRead = {
249
266
  pseudo: config.providers?.translator?.pseudo === true,
250
- glossaryHash: rules.complete ? (source, locale) => (0, glossary_1.glossaryFingerprint)(source, locale, rules.glossary) : undefined,
267
+ glossaryHash: rules.complete ? (source, locale) => (0, translate_1.rulesFingerprint)(source, locale, rules) : undefined,
251
268
  };
252
269
  const partition = (0, lockfile_1.partitionKeys)(lockfile, flatKeys, config.targetLocales, lockfileRead);
253
270
  lockfileStats = (0, lockfile_1.computeLockfileStats)(partition);
@@ -465,7 +482,7 @@ async function runEngineV2(config) {
465
482
  config, startTime, workspace, allTranslatedPerLocale,
466
483
  lockfileStats, tmHits, translationMetadata,
467
484
  translatedThisRun, skippedForBudget, keyUsage,
468
- formatStrings, frameworkConfig, gettext, overrideReport,
485
+ formatStrings, frameworkConfig, gettext, overrideReport, formalityNotes,
469
486
  });
470
487
  return result;
471
488
  }
@@ -590,6 +607,25 @@ function freshTranslations(translation, metadata) {
590
607
  return n;
591
608
  }
592
609
  /** The target locales' files of an adopted setup (null: no file yet). */
610
+ /**
611
+ * For each target locale with no configured form of address, the one its
612
+ * existing file clearly uses (an adopted setup), recorded in
613
+ * `rules.detectedFormality`. Returns a report note per detected locale.
614
+ */
615
+ function detectAdoptedFormality(rules, adopted, targetLocales) {
616
+ const notes = [];
617
+ for (const locale of targetLocales) {
618
+ const file = adopted[locale];
619
+ if (!file || !(0, formality_1.hasFormalitySplit)(locale) || (0, formality_1.formalityFor)(rules.formality, locale))
620
+ continue;
621
+ const detected = (0, formality_1.detectFormality)(Object.values((0, keygen_1.flattenLocaleData)(file.data)).filter((v) => typeof v === 'string'), locale);
622
+ if (!detected)
623
+ continue;
624
+ rules.detectedFormality = { ...rules.detectedFormality, [locale]: detected };
625
+ notes.push(`${locale} formality: ${detected} (detected from the existing translations). Set "formality" in .babelize/config.json to change it.`);
626
+ }
627
+ return notes;
628
+ }
593
629
  function targetFiles(adopted, targetLocales) {
594
630
  return Object.fromEntries(targetLocales.map((l) => [l, adopted[l] ?? null]));
595
631
  }
@@ -603,16 +639,18 @@ function adoptLocales(workspace, adopted, locales, sourceLocale, alsoKeep = [])
603
639
  const source = adopted[sourceLocale];
604
640
  if (!source)
605
641
  return locales;
642
+ // A new language's modules are written like another language's (#370).
643
+ const others = (locale) => Object.fromEntries(Object.entries(adopted).filter(([l]) => l !== locale && l !== sourceLocale));
606
644
  const out = locales.map((l) => {
607
645
  const existing = adopted[l.locale] ?? null;
608
646
  // Without a lockfile the translator returns only the missing keys: the file supplies the rest.
609
647
  const values = { ...(existing ? (0, keygen_1.flattenLocaleData)(existing.data) : {}), ...(0, keygen_1.flattenLocaleData)(l.data) };
610
- return (0, adopted_1.adoptedLocaleFile)(workspace, l.locale, source, values, existing);
648
+ return (0, adopted_1.adoptedLocaleFile)(workspace, l.locale, source, values, existing, others(l.locale));
611
649
  });
612
650
  for (const locale of alsoKeep) {
613
651
  const existing = adopted[locale];
614
652
  if (existing && !out.some((l) => l.locale === locale)) {
615
- out.push((0, adopted_1.adoptedLocaleFile)(workspace, locale, source, (0, keygen_1.flattenLocaleData)(existing.data), existing));
653
+ out.push((0, adopted_1.adoptedLocaleFile)(workspace, locale, source, (0, keygen_1.flattenLocaleData)(existing.data), existing, others(locale)));
616
654
  }
617
655
  }
618
656
  return out;
@@ -620,6 +658,11 @@ function adoptLocales(workspace, adopted, locales, sourceLocale, alsoKeep = [])
620
658
  /** Write each locale file: exact `content` when the engine produced it, else sorted JSON. */
621
659
  async function writeLocales(workspace, locales) {
622
660
  for (const locale of locales) {
661
+ if (locale.files) {
662
+ for (const f of locale.files)
663
+ await fs.outputFile(path.join(workspace.path, f.path), f.content);
664
+ continue;
665
+ }
623
666
  const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale.locale);
624
667
  if (locale.content !== undefined)
625
668
  await fs.outputFile(file, locale.content);
@@ -728,7 +771,7 @@ function mergeChangedFile(list, changed) {
728
771
  existing.hookAdded = existing.hookAdded || changed.hookAdded;
729
772
  }
730
773
  async function finalizePipeline(params) {
731
- const { extraction, keyGeneration, localeHandling, translation, config, startTime, workspace, allTranslatedPerLocale, lockfileStats, tmHits, translationMetadata, formatStrings, frameworkConfig, translatedThisRun, skippedForBudget, keyUsage, gettext, overrideReport, } = params;
774
+ const { extraction, keyGeneration, localeHandling, translation, config, startTime, workspace, allTranslatedPerLocale, lockfileStats, tmHits, translationMetadata, formatStrings, frameworkConfig, translatedThisRun, skippedForBudget, keyUsage, gettext, overrideReport, formalityNotes, } = params;
732
775
  const keyMapping = (0, keygen_1.createKeyMapping)(keyGeneration.keys);
733
776
  // Injection: AST-based i18n hook injection (skipped for frameworks like Django)
734
777
  // An adopted i18n setup is used as it is: no code, config or dependency changes.
@@ -772,6 +815,7 @@ async function finalizePipeline(params) {
772
815
  const finalizationNotes = adoptedSetup
773
816
  ? (0, adopted_1.adoptedSetupNotes)(workspace, config.sourceLocale, config.targetLocales, extraction.notInjected ?? [])
774
817
  : [];
818
+ finalizationNotes.push(...(formalityNotes ?? []));
775
819
  if (gettext) {
776
820
  gettext.refreshReferences(injection);
777
821
  const written = await gettext.write(config.targetLocales, allTranslatedPerLocale, {
@@ -10,8 +10,8 @@ const translator_caller_1 = require("../utils/translator-caller");
10
10
  */
11
11
  function createDefaultTranslationProvider(byokConfig) {
12
12
  return {
13
- async translateBatch({ entries, sourceLang, targetLang, brandVoice, targetLocale, glossary, hints }, options = {}) {
14
- const { translations } = await (0, translator_caller_1.callTranslator)(entries, sourceLang, targetLang, byokConfig, brandVoice, { targetLocale, glossary, hints, signal: options.signal });
13
+ async translateBatch({ entries, sourceLang, targetLang, brandVoice, targetLocale, formality, glossary, hints }, options = {}) {
14
+ const { translations } = await (0, translator_caller_1.callTranslator)(entries, sourceLang, targetLang, byokConfig, brandVoice, { targetLocale, formality, glossary, hints, signal: options.signal });
15
15
  return toKeyResults(entries.map((e) => e.key), translations ?? []);
16
16
  },
17
17
  };
@@ -2,6 +2,7 @@ import type { TranslationEntry } from '../runtime/types';
2
2
  import type { MemoryEntry } from '../modules/translator/memory/types';
3
3
  import type { GlossaryEntryType } from '../modules/glossary/types';
4
4
  import type { TranslationOverride } from '../modules/overrides';
5
+ import type { FormalityLevel, FormalitySetting } from '../modules/translator/formality';
5
6
  /**
6
7
  * Everything the engine needs from the outside world, as interfaces. The
7
8
  * engine never imports a database or cache client: the cloud backend injects
@@ -66,6 +67,8 @@ export interface TranslationBatchRequest {
66
67
  brandVoice?: string;
67
68
  /** Target locale as an ISO code, e.g. "fr" or "pt-BR" (LLM providers only). */
68
69
  targetLocale?: string;
70
+ /** Form of address for the target locale; undefined means auto (LLM providers only). */
71
+ formality?: FormalityLevel;
69
72
  /** Required terminology for this batch: source term → translation (LLM providers only). */
70
73
  glossary?: Array<{
71
74
  term: string;
@@ -129,6 +132,8 @@ export interface GlossaryRule {
129
132
  export interface ProjectRulesStore {
130
133
  getGlossary(projectId: string): Promise<GlossaryRule[]>;
131
134
  getBrandVoice(projectId: string): Promise<string | null>;
135
+ /** Per target locale (or base language) formal/informal/auto address. Optional: absent means auto everywhere. */
136
+ getFormality?(projectId: string): Promise<Record<string, FormalitySetting> | null>;
132
137
  }
133
138
  export interface TranslationOverrideStore {
134
139
  getOverrides(projectId: string): Promise<TranslationOverride[]>;
@@ -1,9 +1,16 @@
1
1
  import { type LocaleGlossary, type LocaleIssue, type LocalePairReport } from './locale-qa';
2
2
  import { type FindLocaleOptions, type LocaleFileSet } from './locale-files';
3
+ import { type FormalitySetting } from '../modules/translator/formality';
4
+ /** Longest brand voice read from `.babelize/config.json` (the cloud setting's limit). */
5
+ export declare const MAX_LOCAL_BRAND_VOICE_CHARS = 300;
3
6
  export interface ProjectLocaleConfig {
4
7
  sourceLocale?: string;
5
8
  targetLocales?: string[];
6
9
  glossary?: LocaleGlossary;
10
+ /** Tone and style for the translator (LLM providers), like a cloud project's brand voice. */
11
+ brandVoice?: string;
12
+ /** Per target locale (or base language): formal, informal or auto address. */
13
+ formality?: Record<string, FormalitySetting>;
7
14
  }
8
15
  /**
9
16
  * The parts of `.babelize/config.json` the local tools use. Missing or
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MAX_LOCAL_BRAND_VOICE_CHARS = void 0;
36
37
  exports.readProjectLocaleConfig = readProjectLocaleConfig;
37
38
  exports.localeIssueFile = localeIssueFile;
38
39
  exports.checkProjectLocales = checkProjectLocales;
@@ -46,6 +47,9 @@ const locale_qa_1 = require("./locale-qa");
46
47
  const locale_files_1 = require("./locale-files");
47
48
  const gettext_files_1 = require("./gettext-files");
48
49
  const locale_names_1 = require("../django/locale-names");
50
+ const formality_1 = require("../modules/translator/formality");
51
+ /** Longest brand voice read from `.babelize/config.json` (the cloud setting's limit). */
52
+ exports.MAX_LOCAL_BRAND_VOICE_CHARS = 300;
49
53
  /**
50
54
  * The parts of `.babelize/config.json` the local tools use. Missing or
51
55
  * malformed config is not an error: everything in it is optional.
@@ -94,6 +98,12 @@ async function readProjectLocaleConfig(projectDir) {
94
98
  }
95
99
  if (neverTranslate.length || alwaysTranslateAs.length)
96
100
  config.glossary = { neverTranslate, alwaysTranslateAs };
101
+ if (typeof raw.brandVoice === 'string' && raw.brandVoice.trim()) {
102
+ config.brandVoice = raw.brandVoice.trim().slice(0, exports.MAX_LOCAL_BRAND_VOICE_CHARS);
103
+ }
104
+ const formality = (0, formality_1.sanitizeFormality)(raw.formality);
105
+ if (formality)
106
+ config.formality = formality;
97
107
  return config;
98
108
  }
99
109
  /** The file a locale issue lives in, relative to the project root. */
@@ -156,7 +166,7 @@ async function checkProjectLocales(projectDir, options = {}) {
156
166
  for (const locale of wanted.filter((l) => set.files[l])) {
157
167
  const target = await (0, locale_files_1.loadLocale)(projectDir, set, locale);
158
168
  fileErrors.push(...target.errors);
159
- locales.push((0, locale_qa_1.checkLocalePair)(source.messages, target.messages, locale, { sourceLocale, glossary, keys: options.keys }));
169
+ locales.push((0, locale_qa_1.checkLocalePair)(source.messages, target.messages, locale, { sourceLocale, glossary, keys: options.keys, formality: config.formality }));
160
170
  }
161
171
  reports.push({
162
172
  dir: set.dir,
@@ -177,7 +187,7 @@ async function checkProjectLocales(projectDir, options = {}) {
177
187
  : [...new Set([...available, ...expected])].filter((l) => l !== sourceLocale).sort();
178
188
  const locales = [];
179
189
  for (const locale of wanted.filter((l) => set.files[l])) {
180
- locales.push((0, locale_qa_1.checkLocalePair)(loaded.source, loaded.byLocale[locale] ?? {}, locale, { sourceLocale, glossary, keys: options.keys }));
190
+ locales.push((0, locale_qa_1.checkLocalePair)(loaded.source, loaded.byLocale[locale] ?? {}, locale, { sourceLocale, glossary, keys: options.keys, formality: config.formality }));
181
191
  }
182
192
  reports.push({
183
193
  dir: set.dir,
@@ -1,7 +1,7 @@
1
1
  export interface LocaleFileSet {
2
2
  /** Directory holding the set, relative to the project root (posix). */
3
3
  dir: string;
4
- layout: 'flat' | 'namespaced';
4
+ layout: 'flat' | 'namespaced' | 'modules';
5
5
  /** locale → files (relative to the project root, posix). */
6
6
  files: Record<string, string[]>;
7
7
  }
@@ -23,21 +23,24 @@ export declare const DEFAULT_LOCALE_IGNORE_DIRS: readonly string[];
23
23
  export interface FindLocaleOptions {
24
24
  /** Directory names to skip at any depth (default DEFAULT_LOCALE_IGNORE_DIRS). */
25
25
  ignoreDirs?: readonly string[];
26
+ /** Also find TypeScript/JS message modules (`<dir>/<locale>/<ns>.ts`). */
27
+ modules?: boolean;
26
28
  }
27
29
  export declare function isLocaleCode(name: string): boolean;
28
30
  /** True when a relative path runs through an ignored directory. */
29
31
  export declare function isIgnoredLocalePath(rel: string, ignoreDirs?: readonly string[]): boolean;
30
32
  /**
31
- * Group relative `.json` paths into locale file sets. Paths that aren't
32
- * `<dir>/<locale>.json` or `<dir>/<locale>/<ns>.json` under a locale folder
33
- * are ignored.
33
+ * Group relative `.json` paths (and, with `modules`, message module paths)
34
+ * into locale file sets. Paths that aren't `<dir>/<locale>.json`,
35
+ * `<dir>/<locale>/<ns>.json` or `<dir>/<locale>/<ns>.ts` under a locale
36
+ * folder are ignored.
34
37
  */
35
38
  export declare function groupLocaleFiles(paths: string[], options?: FindLocaleOptions): LocaleFileSet[];
36
39
  export declare function findLocaleFileSets(projectDir: string, options?: FindLocaleOptions): Promise<LocaleFileSet[]>;
37
40
  /** Reads a project file by relative path; null when it doesn't exist (in that version). */
38
41
  export type ProjectFileReader = (rel: string) => Promise<string | null>;
39
42
  /**
40
- * Read and flatten one locale of a set. Namespaced files are keyed `ns:key`.
43
+ * Read and flatten one locale of a set. Namespaced files and modules are keyed `ns:key`.
41
44
  * `read` reads another version of the files (e.g. from git); by default the
42
45
  * working tree is read.
43
46
  */
@@ -50,11 +50,14 @@ exports.loadLocale = loadLocale;
50
50
  *
51
51
  * locales/en.json, locales/fr.json flat: one file per locale
52
52
  * locales/en/common.json, locales/fr/common.json namespaced (i18next): keys become `common:key`
53
+ * messages/en/auth.ts, messages/fr/auth.ts modules (opt-in): TypeScript/JS message modules,
54
+ * read by AST; `index.*` (the combiner) is not one
53
55
  */
54
56
  const path = __importStar(require("path"));
55
57
  const fs_1 = require("fs");
56
58
  const fast_glob_1 = __importDefault(require("fast-glob"));
57
59
  const locale_qa_1 = require("./locale-qa");
60
+ const message_modules_1 = require("../modules/locale-builder/message-modules");
58
61
  const LOCALE_DIR_NAMES = ['locales', 'locale', 'messages', 'lang', 'langs', 'i18n', 'translations'];
59
62
  /**
60
63
  * Directories never searched for locale files: dependencies, build output,
@@ -77,17 +80,24 @@ function isIgnoredLocalePath(rel, ignoreDirs = exports.DEFAULT_LOCALE_IGNORE_DIR
77
80
  const dirs = rel.split('/').slice(0, -1);
78
81
  return dirs.some((d) => ignoreDirs.includes(d));
79
82
  }
83
+ /** `auth.ts` → `.ts` when it is a message module extension, else null. */
84
+ function moduleExtension(file) {
85
+ if (file.endsWith('.d.ts'))
86
+ return null;
87
+ return message_modules_1.MESSAGE_MODULE_EXTENSIONS.find((ext) => file.endsWith(ext)) ?? null;
88
+ }
80
89
  /**
81
- * Group relative `.json` paths into locale file sets. Paths that aren't
82
- * `<dir>/<locale>.json` or `<dir>/<locale>/<ns>.json` under a locale folder
83
- * are ignored.
90
+ * Group relative `.json` paths (and, with `modules`, message module paths)
91
+ * into locale file sets. Paths that aren't `<dir>/<locale>.json`,
92
+ * `<dir>/<locale>/<ns>.json` or `<dir>/<locale>/<ns>.ts` under a locale
93
+ * folder are ignored.
84
94
  */
85
95
  function groupLocaleFiles(paths, options = {}) {
86
96
  var _a;
87
97
  const ignoreDirs = options.ignoreDirs ?? exports.DEFAULT_LOCALE_IGNORE_DIRS;
88
98
  const sets = new Map();
89
99
  for (const rel of [...new Set(paths.map(toPosix))].sort()) {
90
- if (!rel.endsWith('.json') || isIgnoredLocalePath(rel, ignoreDirs))
100
+ if (isIgnoredLocalePath(rel, ignoreDirs))
91
101
  continue;
92
102
  const parts = rel.split('/');
93
103
  const file = parts[parts.length - 1];
@@ -95,7 +105,21 @@ function groupLocaleFiles(paths, options = {}) {
95
105
  let dir;
96
106
  let locale;
97
107
  let layout;
98
- if (parent !== undefined && LOCALE_DIR_NAMES.includes(parent) && isLocaleCode(file.slice(0, -5))) {
108
+ const moduleExt = options.modules ? moduleExtension(file) : null;
109
+ if (moduleExt) {
110
+ // The combining index module isn't a catalog of its own.
111
+ if (parts.length < 3 || !LOCALE_DIR_NAMES.includes(parts[parts.length - 3]) || !isLocaleCode(parent))
112
+ continue;
113
+ if (file.slice(0, -moduleExt.length) === 'index')
114
+ continue;
115
+ dir = parts.slice(0, -2).join('/');
116
+ locale = parent;
117
+ layout = 'modules';
118
+ }
119
+ else if (!rel.endsWith('.json')) {
120
+ continue;
121
+ }
122
+ else if (parent !== undefined && LOCALE_DIR_NAMES.includes(parent) && isLocaleCode(file.slice(0, -5))) {
99
123
  dir = parts.slice(0, -1).join('/');
100
124
  locale = file.slice(0, -5);
101
125
  layout = 'flat';
@@ -118,7 +142,10 @@ function groupLocaleFiles(paths, options = {}) {
118
142
  async function findLocaleFileSets(projectDir, options = {}) {
119
143
  const names = `{${LOCALE_DIR_NAMES.join(',')}}`;
120
144
  const ignoreDirs = options.ignoreDirs ?? exports.DEFAULT_LOCALE_IGNORE_DIRS;
121
- const found = await (0, fast_glob_1.default)([`**/${names}/*.json`, `**/${names}/*/*.json`], {
145
+ const patterns = [`**/${names}/*.json`, `**/${names}/*/*.json`];
146
+ if (options.modules)
147
+ patterns.push(`**/${names}/*/*.{${message_modules_1.MESSAGE_MODULE_EXTENSIONS.map((e) => e.slice(1)).join(',')}}`);
148
+ const found = await (0, fast_glob_1.default)(patterns, {
122
149
  cwd: projectDir,
123
150
  ignore: ignoreDirs.map((d) => `**/${d}/**`),
124
151
  onlyFiles: true,
@@ -128,7 +155,7 @@ async function findLocaleFileSets(projectDir, options = {}) {
128
155
  return groupLocaleFiles(found, options);
129
156
  }
130
157
  /**
131
- * Read and flatten one locale of a set. Namespaced files are keyed `ns:key`.
158
+ * Read and flatten one locale of a set. Namespaced files and modules are keyed `ns:key`.
132
159
  * `read` reads another version of the files (e.g. from git); by default the
133
160
  * working tree is read.
134
161
  */
@@ -145,9 +172,10 @@ async function loadLocale(projectDir, set, locale, read = (rel) => fs_1.promises
145
172
  const content = await read(rel);
146
173
  if (content === null)
147
174
  continue;
148
- const data = JSON.parse(content);
175
+ const ext = set.layout === 'modules' ? path.extname(rel) : '.json';
176
+ const data = set.layout === 'modules' ? ((0, message_modules_1.parseMessageModule)(content, toPosix(rel))?.data ?? {}) : JSON.parse(content);
149
177
  const flat = (0, locale_qa_1.flattenLocaleMessages)(data);
150
- const ns = set.layout === 'namespaced' ? path.basename(rel, '.json') : null;
178
+ const ns = set.layout === 'flat' ? null : path.basename(rel, ext);
151
179
  for (const [k, v] of Object.entries(flat))
152
180
  messages[ns ? `${ns}:${k}` : k] = v;
153
181
  }
@@ -1,10 +1,13 @@
1
+ import { type FormalitySetting } from '../modules/translator/formality';
1
2
  export type LocaleIssueCode = 'missing_key' | 'extra_key' | 'empty_value' | 'untranslated' | 'placeholder_mismatch' | 'icu_invalid' | 'icu_mismatch' | 'plural_category_invalid' | 'plural_category_missing' | 'glossary_violation'
2
3
  /** The source text changed but the translation didn't (review of a diff). */
3
4
  | 'stale_translation'
4
5
  /** A translation present at the base of a diff was deleted while the source still has it. */
5
6
  | 'translation_removed'
6
7
  /** Pseudo-localized test output (`--provider pseudo`, ⟦…⟧), not a translation. */
7
- | 'pseudo_translation';
8
+ | 'pseudo_translation'
9
+ /** Formal and informal address mixed within one locale, or the form other than the one set. */
10
+ | 'mixed_formality';
8
11
  export type LocaleIssueSeverity = 'error' | 'warning' | 'info';
9
12
  export interface LocaleIssue {
10
13
  locale: string;
@@ -32,6 +35,12 @@ export interface LocalePairOptions {
32
35
  * detection is limited to them too.
33
36
  */
34
37
  keys?: string[];
38
+ /**
39
+ * Configured form of address per locale (or base language). Set: strings
40
+ * using the other form are flagged. Auto: the minority form is flagged when
41
+ * a locale mixes both.
42
+ */
43
+ formality?: Record<string, FormalitySetting>;
35
44
  }
36
45
  export interface LocalePairReport {
37
46
  locale: string;
@@ -20,6 +20,7 @@ const rules_1 = require("../modules/glossary/rules");
20
20
  const placeholder_protection_1 = require("../utils/placeholder-protection");
21
21
  const pseudo_markers_1 = require("../utils/pseudo-markers");
22
22
  const icu_spans_1 = require("../utils/icu-spans");
23
+ const formality_1 = require("../modules/translator/formality");
23
24
  const PLURAL_CATEGORIES = ['zero', 'one', 'two', 'few', 'many', 'other'];
24
25
  const PLURAL_SUFFIX = /^(.+)_(zero|one|two|few|many|other)$/;
25
26
  /**
@@ -324,6 +325,14 @@ function checkLocalePair(source, target, locale, options = {}) {
324
325
  continue;
325
326
  push({ key, code: 'extra_key', severity: 'info', message: 'Not in the source locale (stale or renamed key).' });
326
327
  }
328
+ // Form of address is judged over the whole locale (a diff's few keys can't
329
+ // tell which form is the norm); only keys in scope are reported.
330
+ const translations = Object.fromEntries(Object.entries(target).filter(([k, v]) => k in source && v !== source[k]));
331
+ const address = (0, formality_1.formalityIssues)(translations, locale, (0, formality_1.formalityFor)(options.formality, locale));
332
+ for (const [key, message] of Object.entries(address)) {
333
+ if (inScope(key))
334
+ push({ key, code: 'mixed_formality', severity: 'warning', message: `${message}.` });
335
+ }
327
336
  return tallyLocaleIssues({ locale, total, translated, counts: {}, errors: 0, warnings: 0, issues });
328
337
  }
329
338
  /** Recompute `counts`/`errors`/`warnings` from `issues` (after adding issues to a report). */
package/dist/qa/review.js CHANGED
@@ -129,7 +129,7 @@ async function reviewLocaleChanges(projectDir, options = {}) {
129
129
  : new Set([...changedTarget, ...source.added, ...source.changed, ...source.removed.filter((k) => k in tgtNow)].filter((k) => !removed.has(k)));
130
130
  if (keys.size === 0 && removedTarget.length === 0)
131
131
  continue;
132
- const report = (0, locale_qa_1.checkLocalePair)(srcNow, tgtNow, locale, { sourceLocale, glossary, keys: [...keys] });
132
+ const report = (0, locale_qa_1.checkLocalePair)(srcNow, tgtNow, locale, { sourceLocale, glossary, keys: [...keys], formality: config.formality });
133
133
  if (fileDeleted) {
134
134
  report.issues.unshift({
135
135
  locale,
@@ -9,6 +9,7 @@ import type { ByokProvider, FormatLocaleConfig, Framework } from '@babelize/type
9
9
  import type { EngineProviders, TranslationFailure } from '../providers/types';
10
10
  import type { EngineLogger } from '../utils/logger';
11
11
  import type { I18nLibraryId } from '../detection/i18n';
12
+ import type { SourceScope } from '../utils/source-scope';
12
13
  export interface EngineConfigV2 {
13
14
  /** Path to the workspace directory */
14
15
  workspacePath: string;
@@ -26,6 +27,11 @@ export interface EngineConfigV2 {
26
27
  dryRun: boolean;
27
28
  /** Force translation even if locale files exist */
28
29
  forceTranslation?: boolean;
30
+ /**
31
+ * Source files this run may extract from and rewrite. Each list given
32
+ * replaces the same list in `.babelize/config.json` (`--include`/`--exclude`).
33
+ */
34
+ sourceScope?: SourceScope;
29
35
  /**
30
36
  * Most (key, locale) pairs this run may send to the translator: the
31
37
  * caller's credit budget. Pairs past it are left untranslated (not in the
@@ -92,8 +98,19 @@ export interface EngineConfigV2 {
92
98
  }
93
99
  export interface ExistingI18nSetup {
94
100
  library: I18nLibraryId;
95
- /** Directory of the flat `<locale>.json` files, relative to the workspace (posix). */
101
+ /**
102
+ * Directory of the locale files, relative to the workspace (posix):
103
+ * `<localeDir>/<locale>.json` (flat), or one folder per locale holding a
104
+ * file per namespace, `<localeDir>/<locale>/<ns>.json` (namespaced) or
105
+ * TypeScript/JS message modules `<localeDir>/<locale>/<ns>.ts` (modules).
106
+ */
96
107
  localeDir: string;
108
+ /** Unset: flat. */
109
+ layout?: 'flat' | 'namespaced' | 'modules';
110
+ /** Namespaced and modules: the source language's files (`auth.json`, `auth.ts`), in order. */
111
+ namespaces?: string[];
112
+ /** Modules: the source language's combining module (`index.ts`), copied for a new language. */
113
+ indexFile?: string;
97
114
  /**
98
115
  * Code files that list the app's languages by code (a locale registry, a
99
116
  * `supportedLocales` array): a new language may need adding there too.
@@ -115,6 +132,8 @@ export interface WorkspaceInfo {
115
132
  appDir?: string;
116
133
  /** Framework-specific scan exclusions (FrameworkConfig.excludedPatterns); see workspaceExcludes(). */
117
134
  excludedPatterns?: readonly string[];
135
+ /** The project's `include`/`exclude` globs (config.json, or the run's override); see filterToScope(). */
136
+ sourceScope?: SourceScope;
118
137
  packageJson?: Record<string, any>;
119
138
  /** Output locale file format (e.g., 'json' for React, 'po' for Django) */
120
139
  localeFormat: 'json' | 'po' | 'arb';
@@ -251,6 +270,15 @@ export interface LocaleFile {
251
270
  * is the source file of an adopted i18n setup, which a run never rewrites.
252
271
  */
253
272
  noFile?: boolean;
273
+ /**
274
+ * The locale is several files (an adopted setup with a folder per locale,
275
+ * `path` being that folder): hosts write each one's exact content and
276
+ * ignore `content`/`data` for writing.
277
+ */
278
+ files?: Array<{
279
+ path: string;
280
+ content: string;
281
+ }>;
254
282
  /** Further files generated for this locale (e.g. a compiled .mo next to the .po). */
255
283
  extraFiles?: Array<{
256
284
  path: string;