@babelize/engine 0.3.7 → 0.3.8

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 (36) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +11 -1
  3. package/dist/local/hosted-provider.js +1 -0
  4. package/dist/local/translate-core.d.ts +13 -2
  5. package/dist/local/translate-core.js +27 -9
  6. package/dist/local/translate-messages.d.ts +5 -0
  7. package/dist/local/translate-messages.js +1 -1
  8. package/dist/modules/finalization/nextjs-finalize.d.ts +19 -2
  9. package/dist/modules/finalization/nextjs-finalize.js +46 -4
  10. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  11. package/dist/modules/locale-builder/adopted.js +185 -16
  12. package/dist/modules/locale-builder/locales.js +11 -2
  13. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  14. package/dist/modules/locale-builder/message-modules.js +263 -0
  15. package/dist/modules/translator/client/byok.provider.js +8 -2
  16. package/dist/modules/translator/formality.d.ts +40 -0
  17. package/dist/modules/translator/formality.js +313 -0
  18. package/dist/modules/translator/translate.d.ts +18 -0
  19. package/dist/modules/translator/translate.js +78 -11
  20. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  21. package/dist/modules/workspace/existing-setup.js +32 -15
  22. package/dist/orchestrator.js +51 -7
  23. package/dist/providers/default-translation-provider.js +2 -2
  24. package/dist/providers/types.d.ts +5 -0
  25. package/dist/qa/check-project.d.ts +7 -0
  26. package/dist/qa/check-project.js +12 -2
  27. package/dist/qa/locale-files.d.ts +8 -5
  28. package/dist/qa/locale-files.js +37 -9
  29. package/dist/qa/locale-qa.d.ts +10 -1
  30. package/dist/qa/locale-qa.js +9 -0
  31. package/dist/qa/review.js +1 -1
  32. package/dist/runtime/types.d.ts +21 -1
  33. package/dist/types.d.ts +2 -0
  34. package/dist/utils/translator-caller.d.ts +19 -0
  35. package/dist/utils/translator-caller.js +55 -21
  36. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -51,6 +51,8 @@ export type { AnalyzeOptions, AnalyzedString, FrameworkSupport, ProjectAnalysis
51
51
  export { checkLocalePair, flattenLocaleMessages, tallyLocaleIssues } from './qa/locale-qa';
52
52
  export { canonicalLocale, canonicalizeLocaleKeys, containsTerm, localeValue, normalizeGlossary, glossaryFingerprint, } from './modules/glossary';
53
53
  export type { GlossaryRules, GlossaryRuleInput } from './modules/glossary';
54
+ export { detectFormality, formalityFor, formalityInstruction, formalityIssues, formalityOf, hasFormalitySplit, parseFormalityList, sanitizeFormality, } from './modules/translator/formality';
55
+ export type { FormalityLevel, FormalitySetting } from './modules/translator/formality';
54
56
  export type { LocaleGlossary, LocaleIssue, LocaleIssueCode, LocaleIssueSeverity, LocalePairOptions, LocalePairReport, } from './qa/locale-qa';
55
57
  export { DEFAULT_LOCALE_IGNORE_DIRS, findLocaleFileSets, groupLocaleFiles, isIgnoredLocalePath, isLocaleCode, loadLocale } from './qa/locale-files';
56
58
  export type { FindLocaleOptions, LoadedLocale, LocaleFileSet, ProjectFileReader } from './qa/locale-files';
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
22
22
  };
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.CircuitBreaker = exports.validateBatchQuality = exports.validateTranslationQuality = exports.translatorLoadBalancer = exports.warmupTranslator = exports.checkTranslatorHealth = exports.callTranslator = exports.requiredPluralCategories = exports.parseIcu = exports.isIcuMessage = exports.compareIcuMessages = exports.sameProtectedSpans = exports.restoreText = exports.protectText = exports.hasNothingToTranslate = exports.checkTokens = exports.validateRawTokens = exports.sanitizeTranslation = exports.restorePlaceholders = exports.protectPlaceholders = exports.hashString = exports.hasICUSyntax = exports.extractPlaceholders = exports.parseCode = exports.I18N_LIBRARY_NAMES = exports.detectI18n = exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = exports.localRepoFiles = exports.detectStack = exports.saveProjectConfig = exports.saveCachedStrings = exports.getProjectInfo = exports.getBabelizeSummary = exports.detectProjectInfo = exports.addBabelToHistory = exports.formatSyncNotificationMessage = exports.detectSyncIssues = exports.matchFromMemory = exports.setLocaleValue = exports.applyTranslationOverrides = exports.setEngineLogger = exports.runWithEngineLogger = exports.validateWorkspace = exports.scanKeyReferences = exports.RunAbortedError = exports.validateEngineConfigV2 = exports.runEngineV2 = exports.loadBabelizeConfig = exports.BabelizeEngine = void 0;
25
- exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
25
+ exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
26
26
  var BabelizeEngine_1 = require("./BabelizeEngine");
27
27
  Object.defineProperty(exports, "BabelizeEngine", { enumerable: true, get: function () { return BabelizeEngine_1.BabelizeEngine; } });
28
28
  var config_1 = require("./config");
@@ -125,6 +125,16 @@ Object.defineProperty(exports, "containsTerm", { enumerable: true, get: function
125
125
  Object.defineProperty(exports, "localeValue", { enumerable: true, get: function () { return glossary_1.localeValue; } });
126
126
  Object.defineProperty(exports, "normalizeGlossary", { enumerable: true, get: function () { return glossary_1.normalizeGlossary; } });
127
127
  Object.defineProperty(exports, "glossaryFingerprint", { enumerable: true, get: function () { return glossary_1.glossaryFingerprint; } });
128
+ // Formal vs informal address per target language.
129
+ var formality_1 = require("./modules/translator/formality");
130
+ Object.defineProperty(exports, "detectFormality", { enumerable: true, get: function () { return formality_1.detectFormality; } });
131
+ Object.defineProperty(exports, "formalityFor", { enumerable: true, get: function () { return formality_1.formalityFor; } });
132
+ Object.defineProperty(exports, "formalityInstruction", { enumerable: true, get: function () { return formality_1.formalityInstruction; } });
133
+ Object.defineProperty(exports, "formalityIssues", { enumerable: true, get: function () { return formality_1.formalityIssues; } });
134
+ Object.defineProperty(exports, "formalityOf", { enumerable: true, get: function () { return formality_1.formalityOf; } });
135
+ Object.defineProperty(exports, "hasFormalitySplit", { enumerable: true, get: function () { return formality_1.hasFormalitySplit; } });
136
+ Object.defineProperty(exports, "parseFormalityList", { enumerable: true, get: function () { return formality_1.parseFormalityList; } });
137
+ Object.defineProperty(exports, "sanitizeFormality", { enumerable: true, get: function () { return formality_1.sanitizeFormality; } });
128
138
  var locale_files_1 = require("./qa/locale-files");
129
139
  Object.defineProperty(exports, "DEFAULT_LOCALE_IGNORE_DIRS", { enumerable: true, get: function () { return locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS; } });
130
140
  Object.defineProperty(exports, "findLocaleFileSets", { enumerable: true, get: function () { return locale_files_1.findLocaleFileSets; } });
@@ -153,6 +153,7 @@ class HostedTranslationProvider {
153
153
  ...(glossary.length ? { glossary } : {}),
154
154
  ...(Object.keys(hints).length > 0 ? { hints } : {}),
155
155
  ...(request.brandVoice ? { brandVoice: request.brandVoice.slice(0, types_1.TRANSLATE_BATCH_LIMITS.maxBrandVoiceChars) } : {}),
156
+ ...(request.formality ? { formality: request.formality } : {}),
156
157
  });
157
158
  // One key per logical batch, reused by its retries: if an earlier attempt
158
159
  // was answered (and charged) but the response was lost, the server
@@ -1,8 +1,12 @@
1
1
  import type { EngineConfigV2, EngineResultV2 } from '../runtime/types';
2
2
  import type { ProjectRulesStore, TranslationFailure, TranslationProvider } from '../providers/types';
3
3
  import type { LocaleGlossary } from '../qa/locale-qa';
4
- /** A rules store serving a `.babelize/config.json` glossary (no brand voice locally). */
5
- export declare function configRulesStore(glossary: LocaleGlossary): ProjectRulesStore;
4
+ import type { FormalitySetting } from '../modules/translator/formality';
5
+ /** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
6
+ export declare function configRulesStore(glossary: LocaleGlossary | undefined, extra?: {
7
+ brandVoice?: string;
8
+ formality?: Record<string, FormalitySetting>;
9
+ }): ProjectRulesStore;
6
10
  import { type ByokProvider } from '@babelize/types';
7
11
  import type { HostedTranslationProvider } from './hosted-provider';
8
12
  import { type FormatResult } from './formatter';
@@ -32,6 +36,13 @@ export interface LocalTranslateOptions {
32
36
  * brought up to date (from the lockfile, so only new strings cost tokens).
33
37
  */
34
38
  replace?: boolean;
39
+ /**
40
+ * Form of address per target locale (or base language), e.g. `{ de: 'formal' }`
41
+ * (`--formality de=formal`). Merged over `.babelize/config.json` `formality`.
42
+ */
43
+ formality?: Record<string, FormalitySetting>;
44
+ /** Tone and style for the translator; replaces `.babelize/config.json` `brandVoice`. */
45
+ brandVoice?: string;
35
46
  }
36
47
  export interface LocalTranslateDeps {
37
48
  /** Replaces the BYOK translator (tests). */
@@ -52,15 +52,16 @@ const orchestrator_1 = require("../orchestrator");
52
52
  const logger_1 = require("../utils/logger");
53
53
  const workspace_1 = require("../modules/workspace");
54
54
  const check_project_1 = require("../qa/check-project");
55
- /** A rules store serving a `.babelize/config.json` glossary (no brand voice locally). */
56
- function configRulesStore(glossary) {
55
+ /** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
56
+ function configRulesStore(glossary, extra = {}) {
57
57
  const rules = [
58
- ...(glossary.neverTranslate ?? []).map((term) => ({ term, type: 'never_translate', translations: null })),
59
- ...(glossary.alwaysTranslateAs ?? []).map((e) => ({ term: e.term, type: 'always_translate_as', translations: e.translations })),
58
+ ...(glossary?.neverTranslate ?? []).map((term) => ({ term, type: 'never_translate', translations: null })),
59
+ ...(glossary?.alwaysTranslateAs ?? []).map((e) => ({ term: e.term, type: 'always_translate_as', translations: e.translations })),
60
60
  ];
61
61
  return {
62
62
  getGlossary: async () => rules,
63
- getBrandVoice: async () => null,
63
+ getBrandVoice: async () => extra.brandVoice?.trim() || null,
64
+ getFormality: async () => (extra.formality && Object.keys(extra.formality).length > 0 ? extra.formality : null),
64
65
  };
65
66
  }
66
67
  const types_1 = require("@babelize/types");
@@ -334,10 +335,15 @@ async function runScoped(opts, deps, engineLog, state) {
334
335
  const targetLocales = [...opts.targetLocales, ...keptLocales];
335
336
  const before = await (0, workspace_copy_1.snapshot)(temp.dir);
336
337
  state.collecting = true;
337
- // The project's glossary from .babelize/config.json — the same file and
338
- // schema `babelize check` reads — applied like a cloud project's.
339
- const { glossary } = await (0, check_project_1.readProjectLocaleConfig)(projectDir);
340
- const rules = glossary ? configRulesStore(glossary) : undefined;
338
+ // The project's glossary, brand voice and formality from
339
+ // .babelize/config.json — the same file and schema `babelize check`
340
+ // reads — applied like a cloud project's. Options win over the file.
341
+ const config = await (0, check_project_1.readProjectLocaleConfig)(projectDir);
342
+ const brandVoice = opts.brandVoice?.trim() || config.brandVoice;
343
+ const formality = { ...config.formality, ...opts.formality };
344
+ const rules = config.glossary || brandVoice || Object.keys(formality).length > 0
345
+ ? configRulesStore(config.glossary, { brandVoice, formality })
346
+ : undefined;
341
347
  const runEngine = deps.runEngine ?? orchestrator_1.runEngineV2;
342
348
  const result = await runEngine({
343
349
  workspacePath: temp.dir,
@@ -390,6 +396,18 @@ async function runScoped(opts, deps, engineLog, state) {
390
396
  if (locale.locale === opts.sourceLocale || locale.noFile)
391
397
  continue;
392
398
  const rel = locale.path.split(path.sep).join('/');
399
+ if (locale.files) {
400
+ // An adopted folder per locale (#370): each namespace file or module
401
+ // exactly as the engine produced it, existing translations kept.
402
+ for (const f of locale.files) {
403
+ const abs = path.resolve(temp.dir, f.path.split(path.sep).join('/'));
404
+ if (path.relative(temp.dir, abs).startsWith('..'))
405
+ continue;
406
+ await (0, promises_1.mkdir)(path.dirname(abs), { recursive: true });
407
+ await (0, promises_1.writeFile)(abs, f.content);
408
+ }
409
+ continue;
410
+ }
393
411
  if (locale.content !== undefined && !rel.endsWith('.json')) {
394
412
  // A merged catalogue (Django .po): written exactly as the engine
395
413
  // produced it. The merge never drops existing translations.
@@ -1,5 +1,6 @@
1
1
  import type { ByokProvider } from '@babelize/types';
2
2
  import type { TranslationFailure, TranslationProvider } from '../providers/types';
3
+ import type { FormalitySetting } from '../modules/translator/formality';
3
4
  /**
4
5
  * Translate a flat key → text map with the engine's translate phase, without
5
6
  * a project: the same placeholder protection, ICU/plural handling, glossary,
@@ -25,6 +26,10 @@ export interface TranslateMessagesOptions {
25
26
  translations: Record<string, string>;
26
27
  }>;
27
28
  };
29
+ /** Tone and style for the translator (LLM providers). */
30
+ brandVoice?: string;
31
+ /** Form of address per target locale (or base language), e.g. `{ de: 'formal' }`. */
32
+ formality?: Record<string, FormalitySetting>;
28
33
  /**
29
34
  * The app's runtime formats ICU (next-intl, i18next-icu): count
30
35
  * placeholders may become plurals. Default true.
@@ -70,7 +70,7 @@ async function run(opts) {
70
70
  localeFormat: 'json',
71
71
  };
72
72
  const result = await (0, translate_1.translateLocales)(workspace, { locale: opts.sourceLocale, path: '', data: { ...opts.messages }, isNew: false }, opts.targetLocales, false, true, // dry run: nothing written
73
- undefined, opts.onProgress, undefined, undefined, opts.translator ? undefined : opts.byok, undefined, undefined, opts.translator ? { translator: opts.translator } : {}, { targetPlurals: opts.targetPlurals ?? true, rules: { glossary, brandVoice: null, complete: true } });
73
+ undefined, opts.onProgress, undefined, undefined, opts.translator ? undefined : opts.byok, undefined, undefined, opts.translator ? { translator: opts.translator } : {}, { targetPlurals: opts.targetPlurals ?? true, rules: { glossary, brandVoice: opts.brandVoice?.trim() || null, formality: opts.formality ?? null, complete: true } });
74
74
  const targets = {};
75
75
  for (const file of result.translation.locales) {
76
76
  const flat = (0, keygen_1.flattenLocaleData)(file.data);
@@ -30,8 +30,25 @@ export declare function buildRequestConfig(opts: {
30
30
  }): string;
31
31
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
32
32
  export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
33
- /** Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>. */
34
- export declare function wrapRootLayout(content: string, typescript: boolean): string | null;
33
+ /**
34
+ * True when next.config turns on Cache Components (`cacheComponents: true`,
35
+ * the default in create-next-app 16.4+, or `experimental.dynamicIO` before
36
+ * Next 16). Then request data — the cookies and headers our request config
37
+ * reads — may only be read inside <Suspense>, or `next build` fails with
38
+ * "Next.js encountered uncached or runtime data during prerendering".
39
+ */
40
+ export declare function usesCacheComponents(nextConfig: string): boolean;
41
+ /**
42
+ * Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
43
+ *
44
+ * With `suspense` (Cache Components on), the whole <body> content is wrapped
45
+ * in <Suspense><NextIntlClientProvider>…, so every translated component —
46
+ * including a header or footer rendered by the layout itself — reads the
47
+ * locale inside a Suspense boundary.
48
+ */
49
+ export declare function wrapRootLayout(content: string, typescript: boolean, options?: {
50
+ suspense?: boolean;
51
+ }): string | null;
35
52
  export declare function finalizeNextIntl(workspace: WorkspaceInfo, dryRun: boolean, options: {
36
53
  sourceLocale?: string;
37
54
  targetLocales?: string[];
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.NEXT_INTL_DEPENDENCIES = void 0;
37
37
  exports.buildRequestConfig = buildRequestConfig;
38
38
  exports.wrapNextConfig = wrapNextConfig;
39
+ exports.usesCacheComponents = usesCacheComponents;
39
40
  exports.wrapRootLayout = wrapRootLayout;
40
41
  exports.finalizeNextIntl = finalizeNextIntl;
41
42
  const fs = __importStar(require("fs"));
@@ -179,8 +180,25 @@ function wrapNextConfig(content, requestConfigPath, typescript) {
179
180
  }
180
181
  return null;
181
182
  }
182
- /** Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>. */
183
- function wrapRootLayout(content, typescript) {
183
+ /**
184
+ * True when next.config turns on Cache Components (`cacheComponents: true`,
185
+ * the default in create-next-app 16.4+, or `experimental.dynamicIO` before
186
+ * Next 16). Then request data — the cookies and headers our request config
187
+ * reads — may only be read inside <Suspense>, or `next build` fails with
188
+ * "Next.js encountered uncached or runtime data during prerendering".
189
+ */
190
+ function usesCacheComponents(nextConfig) {
191
+ return /\b(cacheComponents|dynamicIO)\s*:\s*true\b/.test(nextConfig);
192
+ }
193
+ /**
194
+ * Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
195
+ *
196
+ * With `suspense` (Cache Components on), the whole <body> content is wrapped
197
+ * in <Suspense><NextIntlClientProvider>…, so every translated component —
198
+ * including a header or footer rendered by the layout itself — reads the
199
+ * locale inside a Suspense boundary.
200
+ */
201
+ function wrapRootLayout(content, typescript, options = {}) {
184
202
  if (content.includes('NextIntlClientProvider'))
185
203
  return content;
186
204
  let ast;
@@ -191,11 +209,16 @@ function wrapRootLayout(content, typescript) {
191
209
  return null;
192
210
  }
193
211
  let target = null;
212
+ let bodyContent = null;
194
213
  (0, ast_helpers_1.traverse)(ast, {
195
214
  JSXElement(p) {
196
215
  const name = p.node.openingElement.name;
197
216
  if (!ast_helpers_1.t.isJSXIdentifier(name, { name: 'body' }))
198
217
  return;
218
+ const { openingElement, closingElement } = p.node;
219
+ if (openingElement.end != null && closingElement?.start != null) {
220
+ bodyContent = { start: openingElement.end, end: closingElement.start };
221
+ }
199
222
  p.traverse({
200
223
  JSXExpressionContainer(inner) {
201
224
  if (ast_helpers_1.t.isIdentifier(inner.node.expression, { name: 'children' }) && inner.node.start != null && inner.node.end != null) {
@@ -209,6 +232,19 @@ function wrapRootLayout(content, typescript) {
209
232
  });
210
233
  if (!target)
211
234
  return null;
235
+ if (options.suspense && bodyContent) {
236
+ const { start, end } = bodyContent;
237
+ const importsSuspense = /import\s*\{[^}]*\bSuspense\b[^}]*\}\s*from\s*['"]react['"]/.test(content);
238
+ const imports = [
239
+ ...(importsSuspense ? [] : [`import { Suspense } from 'react';`]),
240
+ `import { NextIntlClientProvider } from 'next-intl';`,
241
+ ].join('\n');
242
+ return applySplices(content, [
243
+ insertTopLevel(ast, imports),
244
+ { at: start, insert: '<Suspense><NextIntlClientProvider>' },
245
+ { at: end, insert: '</NextIntlClientProvider></Suspense>' },
246
+ ]);
247
+ }
212
248
  const { start, end } = target;
213
249
  return applySplices(content, [
214
250
  insertTopLevel(ast, `import { NextIntlClientProvider } from 'next-intl';`),
@@ -290,6 +326,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
290
326
  // 2. next.config — wrap with the next-intl plugin.
291
327
  const pluginPath = `./${toPosix(path.relative(root, requestFile))}`;
292
328
  const nextConfigPath = await findFirst(root, NEXT_CONFIG_FILES);
329
+ const cacheComponents = nextConfigPath ? usesCacheComponents(await (0, file_utils_1.readFile)(nextConfigPath)) : false;
293
330
  if (!nextConfigPath) {
294
331
  const created = `import createNextIntlPlugin from 'next-intl/plugin';\n\n` +
295
332
  `const withNextIntl = createNextIntlPlugin(${JSON.stringify(pluginPath)});\n\n` +
@@ -316,9 +353,14 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
316
353
  }
317
354
  else {
318
355
  const content = await (0, file_utils_1.readFile)(layoutPath);
319
- const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath));
356
+ const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath), { suspense: cacheComponents });
357
+ const layoutName = toPosix(path.relative(root, layoutPath));
358
+ if (cacheComponents && content.includes('NextIntlClientProvider') && !/<Suspense\b/.test(content)) {
359
+ warnings.push(`next.config enables cacheComponents, and ${layoutName} renders NextIntlClientProvider outside <Suspense>. ` +
360
+ 'next-intl reads the locale from cookies and headers here, so wrap the <body> content in <Suspense> or next build fails.');
361
+ }
320
362
  if (wrapped === null) {
321
- warnings.push(`Could not find {children} inside <body> in ${toPosix(path.relative(root, layoutPath))}: ` +
363
+ warnings.push(`Could not find {children} inside <body> in ${layoutName}: ` +
322
364
  'wrap it in <NextIntlClientProvider> from next-intl so Client Components can translate.');
323
365
  }
324
366
  else if (wrapped !== content) {
@@ -1,18 +1,42 @@
1
1
  import type { ExtractedString, LocaleData, LocaleFile, NotInjectedString, WorkspaceInfo } from '../../runtime/types';
2
2
  import type { LockfileData } from '../lockfile/schema';
3
+ import { type MessageModule } from './message-modules';
3
4
  export interface AdoptedLocale {
5
+ /** Namespaced and modules layouts: `{ <namespace>: <that file's messages> }`. */
4
6
  data: LocaleData;
7
+ /** Flat layout: the file's content. */
5
8
  raw: string;
9
+ /** Namespaced and modules layouts: the locale's files, by namespace. */
10
+ parts?: Record<string, AdoptedPart>;
11
+ /** Modules: the locale's combining module (`index.ts`) as written. */
12
+ indexRaw?: string;
13
+ }
14
+ export interface AdoptedPart {
15
+ /** File name in the locale's folder (`auth.json`, `auth.ts`). */
16
+ file: string;
17
+ raw: string;
18
+ data: LocaleData;
19
+ /** Modules: where each string sits, to write a module like this one. */
20
+ module?: MessageModule;
6
21
  }
7
22
  /** The locale files as they are before the run (the translator writes to the same paths). */
8
23
  export declare function readAdoptedLocales(workspace: WorkspaceInfo, locales: string[]): Promise<Record<string, AdoptedLocale | null>>;
24
+ export declare function readAdoptedLocale(workspace: WorkspaceInfo, locale: string): Promise<AdoptedLocale | null>;
9
25
  /**
10
26
  * Record the translations already in the project's locale files in the
11
27
  * lockfile, so they are reused instead of re-translated. A file value wins
12
28
  * over the lockfile's (someone edited the file); a key whose source text
13
29
  * changed since the lockfile recorded it is left for re-translation.
14
30
  */
15
- export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): LockfileData;
31
+ export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>, options?: {
32
+ /**
33
+ * Only replace translations the lockfile already recorded (files Babelize
34
+ * generated itself): a value it never recorded — a backup-translator
35
+ * draft, or a failed key — is retried as usual, and so is a recorded copy
36
+ * of the source text.
37
+ */
38
+ onlyOverRecorded?: boolean;
39
+ }): LockfileData;
16
40
  /** Keys of `source` missing (or empty) in each target file: the work for a run without a lockfile. */
17
41
  export declare function missingKeysByLocale(flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): Record<string, string[]>;
18
42
  /**
@@ -20,8 +44,11 @@ export declare function missingKeysByLocale(flatKeys: Record<string, string>, ta
20
44
  * extra keys, non-string values) with `values` filled in, or — for a new
21
45
  * file — the source file's structure and order. Serialized like the source
22
46
  * file (indentation, trailing newline) and handed to hosts as exact content.
47
+ * `others` are the setup's other locales, whose modules can serve as the
48
+ * template for a new language's (they already import the source and say
49
+ * `satisfies`).
23
50
  */
24
- export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null): LocaleFile;
51
+ export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null, others?: Record<string, AdoptedLocale | null>): LocaleFile;
25
52
  /**
26
53
  * What the user needs to know after translating an adopted setup: where the
27
54
  * translations went, strings in the code that aren't wired up, and where a
@@ -1,6 +1,40 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.readAdoptedLocales = readAdoptedLocales;
37
+ exports.readAdoptedLocale = readAdoptedLocale;
4
38
  exports.seedLockfileFromLocaleFiles = seedLockfileFromLocaleFiles;
5
39
  exports.missingKeysByLocale = missingKeysByLocale;
6
40
  exports.adoptedLocaleFile = adoptedLocaleFile;
@@ -8,36 +42,94 @@ exports.adoptedSetupNotes = adoptedSetupNotes;
8
42
  exports.hardcodedStrings = hardcodedStrings;
9
43
  /**
10
44
  * Locale files of an adopted i18n setup (#367): the app's own `<locale>.json`
11
- * files in its own locale directory. Their translations are the project's —
45
+ * files in its own locale directory, or a folder per locale of namespace
46
+ * files — JSON, or TypeScript/JS message modules (#370). Their translations are the project's —
12
47
  * kept, never re-translated while their source text is unchanged — and a run
13
48
  * writes them back in the file's own key order and indentation, with nothing
14
49
  * Babelize-specific (`_meta`) added.
15
50
  */
16
51
  const fs_1 = require("fs");
52
+ const path = __importStar(require("path"));
17
53
  const i18n_1 = require("../../detection/i18n");
18
54
  const file_utils_1 = require("../../utils/file-utils");
19
55
  const keygen_1 = require("../keygen");
20
56
  const hasher_1 = require("../lockfile/hasher");
21
57
  const language_codes_1 = require("../translator/language-codes");
58
+ const message_modules_1 = require("./message-modules");
22
59
  /** The locale files as they are before the run (the translator writes to the same paths). */
23
60
  async function readAdoptedLocales(workspace, locales) {
24
61
  const out = {};
25
- for (const locale of locales) {
26
- const raw = await fs_1.promises.readFile((0, file_utils_1.workspaceLocaleFile)(workspace, locale).file, 'utf8').catch(() => null);
27
- let data = null;
28
- if (raw !== null) {
62
+ for (const locale of locales)
63
+ out[locale] = await readAdoptedLocale(workspace, locale);
64
+ return out;
65
+ }
66
+ async function readAdoptedLocale(workspace, locale) {
67
+ const setup = workspace.existingSetup;
68
+ if (setup?.layout && setup.layout !== 'flat')
69
+ return readLocaleFolder(workspace, locale);
70
+ const raw = await fs_1.promises.readFile((0, file_utils_1.workspaceLocaleFile)(workspace, locale).file, 'utf8').catch(() => null);
71
+ if (raw === null)
72
+ return null;
73
+ const data = parseJsonObject(raw, (0, file_utils_1.workspaceLocaleFile)(workspace, locale).relativeFile);
74
+ return data ? { data, raw } : null;
75
+ }
76
+ /** A locale's folder of namespace files: those the source language has. */
77
+ async function readLocaleFolder(workspace, locale) {
78
+ const setup = workspace.existingSetup;
79
+ const parts = {};
80
+ const data = {};
81
+ for (const file of setup.namespaces ?? []) {
82
+ const rel = adoptedFilePath(setup.localeDir, locale, file);
83
+ const raw = await fs_1.promises.readFile(path.join(workspace.path, rel), 'utf8').catch(() => null);
84
+ if (raw === null)
85
+ continue;
86
+ const ns = namespaceOf(file);
87
+ if (setup.layout === 'modules') {
88
+ let module;
29
89
  try {
30
- const parsed = JSON.parse(raw);
31
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
32
- data = parsed;
90
+ module = (0, message_modules_1.parseMessageModule)(raw, rel);
33
91
  }
34
- catch {
35
- throw new Error(`${(0, file_utils_1.workspaceLocaleFile)(workspace, locale).relativeFile} is not valid JSON. Fix it and run again. Nothing was changed.`);
92
+ catch (err) {
93
+ if (!(err instanceof message_modules_1.MessageModuleError))
94
+ throw err;
95
+ throw new Error(`Babelize can't read the ${i18n_1.I18N_LIBRARY_NAMES[setup.library]} messages in ${setup.localeDir}/<locale>/*${path.extname(file)}: ${err.message} ` +
96
+ `Messages must be an exported object of plain text values. Nothing was changed.`);
36
97
  }
98
+ // Not a catalog (types, helpers): left alone.
99
+ if (!module)
100
+ continue;
101
+ parts[ns] = { file, raw, data: module.data, module };
37
102
  }
38
- out[locale] = data && raw !== null ? { data, raw } : null;
103
+ else {
104
+ const parsed = parseJsonObject(raw, rel);
105
+ if (!parsed)
106
+ continue;
107
+ parts[ns] = { file, raw, data: parsed };
108
+ }
109
+ data[ns] = parts[ns].data;
110
+ }
111
+ if (Object.keys(parts).length === 0)
112
+ return null;
113
+ const indexRaw = setup.indexFile
114
+ ? await fs_1.promises.readFile(path.join(workspace.path, adoptedFilePath(setup.localeDir, locale, setup.indexFile)), 'utf8').catch(() => undefined)
115
+ : undefined;
116
+ return { data, raw: '', parts, ...(indexRaw !== undefined ? { indexRaw } : {}) };
117
+ }
118
+ function parseJsonObject(raw, rel) {
119
+ try {
120
+ const parsed = JSON.parse(raw);
121
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
122
+ }
123
+ catch {
124
+ throw new Error(`${rel} is not valid JSON. Fix it and run again. Nothing was changed.`);
39
125
  }
40
- return out;
126
+ }
127
+ /** `messages/fr/auth.ts`, relative to the workspace (posix). */
128
+ function adoptedFilePath(localeDir, locale, file) {
129
+ return path.posix.join(localeDir, locale, file);
130
+ }
131
+ function namespaceOf(file) {
132
+ return file.slice(0, file.length - path.extname(file).length);
41
133
  }
42
134
  /**
43
135
  * Record the translations already in the project's locale files in the
@@ -45,7 +137,7 @@ async function readAdoptedLocales(workspace, locales) {
45
137
  * over the lockfile's (someone edited the file); a key whose source text
46
138
  * changed since the lockfile recorded it is left for re-translation.
47
139
  */
48
- function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets) {
140
+ function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets, options = {}) {
49
141
  const next = JSON.parse(JSON.stringify(lockfile));
50
142
  const now = new Date().toISOString();
51
143
  for (const [locale, file] of Object.entries(targets)) {
@@ -59,6 +151,11 @@ function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets) {
59
151
  const entry = next.keys[key] ?? { sourceHash: hash, translatedAt: now, languages: {}, metadata: {} };
60
152
  if (entry.sourceHash !== hash)
61
153
  continue;
154
+ if (options.onlyOverRecorded) {
155
+ const recorded = entry.languages[locale];
156
+ if (!recorded || recorded === source)
157
+ continue;
158
+ }
62
159
  if (entry.languages[locale] !== value) {
63
160
  // Not what Babelize wrote: the project's own, kept through glossary edits too.
64
161
  entry.metadata = { ...(entry.metadata ?? {}), [locale]: { external: true } };
@@ -83,8 +180,13 @@ function missingKeysByLocale(flatKeys, targets) {
83
180
  * extra keys, non-string values) with `values` filled in, or — for a new
84
181
  * file — the source file's structure and order. Serialized like the source
85
182
  * file (indentation, trailing newline) and handed to hosts as exact content.
183
+ * `others` are the setup's other locales, whose modules can serve as the
184
+ * template for a new language's (they already import the source and say
185
+ * `satisfies`).
86
186
  */
87
- function adoptedLocaleFile(workspace, locale, source, values, existing) {
187
+ function adoptedLocaleFile(workspace, locale, source, values, existing, others = {}) {
188
+ if (source.parts)
189
+ return adoptedLocaleFolder(workspace, locale, source, values, existing, others);
88
190
  const data = (fill(existing ? clone(existing.data) : {}, source.data, values, '', !existing) ?? {});
89
191
  const style = existing ?? source;
90
192
  const { relativeFile } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
@@ -96,9 +198,67 @@ function adoptedLocaleFile(workspace, locale, source, values, existing) {
96
198
  data,
97
199
  isNew: !existing,
98
200
  isRTL: (0, language_codes_1.isRTL)(locale),
99
- content: unchanged ? existing.raw : `${JSON.stringify(data, null, indentOf(style.raw))}${style.raw.endsWith('\n') ? '\n' : ''}`,
201
+ content: unchanged ? existing.raw : serializeJson(data, style.raw),
100
202
  };
101
203
  }
204
+ /** A folder-per-locale target: one file per source namespace (plus the index module for a new language). */
205
+ function adoptedLocaleFolder(workspace, locale, source, values, existing, others) {
206
+ const setup = workspace.existingSetup;
207
+ const files = [];
208
+ const data = {};
209
+ for (const [ns, sourcePart] of Object.entries(source.parts)) {
210
+ const before = existing?.parts?.[ns];
211
+ // Each file on its own: a namespace file new to this language gets the source's non-text values.
212
+ const partData = fill(before ? clone(before.data) : {}, sourcePart.data, values, ns, !before);
213
+ if (!partData || typeof partData !== 'object' || Array.isArray(partData))
214
+ continue;
215
+ // No translation for a file this language doesn't have: not created.
216
+ if (!before && Object.keys((0, keygen_1.flattenLocaleData)(partData)).length === 0)
217
+ continue;
218
+ data[ns] = partData;
219
+ const rel = adoptedFilePath(setup.localeDir, locale, sourcePart.file);
220
+ if (before && JSON.stringify(partData) === JSON.stringify(before.data)) {
221
+ files.push({ path: rel, content: before.raw });
222
+ continue;
223
+ }
224
+ if (!sourcePart.module) {
225
+ files.push({ path: rel, content: serializeJson(partData, (before ?? sourcePart).raw) });
226
+ continue;
227
+ }
228
+ const flat = (0, keygen_1.flattenLocaleData)(partData);
229
+ const template = moduleTemplate(ns, Object.keys(flat), before, others, sourcePart);
230
+ files.push({ path: rel, content: (0, message_modules_1.writeMessageModule)(template.raw, template.module, flat) });
231
+ }
232
+ // A new language's folder gets the combining module too, copied from a sibling.
233
+ if (setup.indexFile && !existing) {
234
+ const from = Object.entries(others).find(([, o]) => o?.indexRaw !== undefined)?.[1]?.indexRaw ?? source.indexRaw;
235
+ if (from !== undefined)
236
+ files.push({ path: adoptedFilePath(setup.localeDir, locale, setup.indexFile), content: from });
237
+ }
238
+ return {
239
+ locale,
240
+ path: path.posix.join(setup.localeDir, locale),
241
+ data,
242
+ isNew: !existing,
243
+ isRTL: (0, language_codes_1.isRTL)(locale),
244
+ files,
245
+ };
246
+ }
247
+ /**
248
+ * The module to write a target's from: the target's own (new keys are added
249
+ * to it), else another language's that has every key (written as a
250
+ * translation of the source, e.g. `satisfies MessageShape<typeof english>`),
251
+ * else any other language's, else the source's.
252
+ */
253
+ function moduleTemplate(ns, keys, own, others, sourcePart) {
254
+ if (own?.module)
255
+ return own;
256
+ const siblings = Object.keys(others).sort().map((l) => others[l]?.parts?.[ns]).filter((p) => p?.module);
257
+ return siblings.find((p) => keys.every((k) => p.module.leaves[k])) ?? siblings[0] ?? sourcePart;
258
+ }
259
+ function serializeJson(data, styleRaw) {
260
+ return `${JSON.stringify(data, null, indentOf(styleRaw))}${styleRaw.endsWith('\n') ? '\n' : ''}`;
261
+ }
102
262
  /**
103
263
  * Walk the source structure, writing translated leaves into `target` (new
104
264
  * keys land in source order). Undefined: nothing to write at this path.
@@ -153,15 +313,24 @@ function adoptedSetupNotes(workspace, sourceLocale, targetLocales, hardcoded) {
153
313
  const notes = [`Used the project's existing ${library} setup: translations are in ${setup.localeDir}/. No code or i18n config was changed.`];
154
314
  if (hardcoded.length > 0) {
155
315
  const files = new Set(hardcoded.map((h) => h.file)).size;
156
- notes.push(`${hardcoded.length} hardcoded string(s) in ${files} file(s) look translatable but aren't in ${setup.localeDir}/${sourceLocale}.json. ` +
316
+ notes.push(`${hardcoded.length} hardcoded string(s) in ${files} file(s) look translatable but aren't in ${sourceFiles(setup, sourceLocale)}. ` +
157
317
  `They were left as they are: add them to your ${library} setup to translate them.`);
158
318
  }
159
319
  const added = targetLocales.filter((l) => !workspace.existingLocales.includes(l));
160
320
  if (added.length > 0 && setup.languageLists.length > 0) {
161
321
  notes.push(`New language(s) ${added.join(', ')}: add them where the app lists its languages (${setup.languageLists.join(', ')}), or the app won't offer them.`);
162
322
  }
323
+ else if (added.length > 0 && setup.layout && setup.layout !== 'flat') {
324
+ notes.push(`New language(s) ${added.join(', ')}: register them where the app loads ${setup.localeDir}/<locale>/ (its list of locales and message imports), or the app won't offer them.`);
325
+ }
163
326
  return notes;
164
327
  }
328
+ /** Where an adopted setup's source text is, for messages. */
329
+ function sourceFiles(setup, sourceLocale) {
330
+ if (!setup.layout || setup.layout === 'flat')
331
+ return `${setup.localeDir}/${sourceLocale}.json`;
332
+ return `${setup.localeDir}/${sourceLocale}/`;
333
+ }
165
334
  const COMPONENT_FILE = /\.(?:vue|jsx|tsx|html?)$/;
166
335
  /**
167
336
  * Strings found in code that an adopted setup leaves alone (reported, never