@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
@@ -1,4 +1,5 @@
1
1
  import type { ExtractedString } from '../runtime/types';
2
+ import type { SourceScope } from '../utils/source-scope';
2
3
  export type FrameworkSupport = 'supported' | 'beta' | 'unsupported';
3
4
  /** How well `babelize translate` handles a detected framework. */
4
5
  export declare function frameworkSupport(framework: string): FrameworkSupport;
@@ -95,6 +96,8 @@ export interface AnalyzeOptions {
95
96
  targetLocales?: string[];
96
97
  /** Parent dir for the temp copy (default: OS temp dir). */
97
98
  tmpRoot?: string;
99
+ /** Source files to analyze; each list given replaces `.babelize/config.json` `include`/`exclude`. */
100
+ sourceScope?: SourceScope;
98
101
  }
99
102
  /** Analyze `projectDir` on a temp copy; the project itself is only read. */
100
103
  export declare function analyzeProject(projectDir: string, options?: AnalyzeOptions): Promise<ProjectAnalysis>;
@@ -131,6 +131,7 @@ async function analyzeWorkspace(workspacePath, options = {}) {
131
131
  targetLocales,
132
132
  confidenceThreshold: 80,
133
133
  dryRun: true,
134
+ ...(options.sourceScope ? { sourceScope: options.sourceScope } : {}),
134
135
  }));
135
136
  }
136
137
  catch (err) {
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';
@@ -59,4 +61,6 @@ export type { LocaleChangeReview, LocaleSetChangeReview, ReviewOptions } from '.
59
61
  export { checkProjectLocales, localeIssueFile, readProjectLocaleConfig } from './qa/check-project';
60
62
  export type { CheckProjectOptions, LocaleSetReport, ProjectLocaleCheck, ProjectLocaleConfig } from './qa/check-project';
61
63
  export { hashText, translationCacheKey, TRANSLATION_CACHE_TTL_SECONDS } from './utils/cache-keys';
64
+ export { createScopeMatcher, mergeSourceScope, normalizeScopePatterns, readSourceScope } from './utils/source-scope';
65
+ export type { SourceScope } from './utils/source-scope';
62
66
  export * from './local';
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.readSourceScope = exports.normalizeScopePatterns = exports.mergeSourceScope = exports.createScopeMatcher = 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; } });
@@ -143,5 +153,10 @@ var cache_keys_1 = require("./utils/cache-keys");
143
153
  Object.defineProperty(exports, "hashText", { enumerable: true, get: function () { return cache_keys_1.hashText; } });
144
154
  Object.defineProperty(exports, "translationCacheKey", { enumerable: true, get: function () { return cache_keys_1.translationCacheKey; } });
145
155
  Object.defineProperty(exports, "TRANSLATION_CACHE_TTL_SECONDS", { enumerable: true, get: function () { return cache_keys_1.TRANSLATION_CACHE_TTL_SECONDS; } });
156
+ var source_scope_1 = require("./utils/source-scope");
157
+ Object.defineProperty(exports, "createScopeMatcher", { enumerable: true, get: function () { return source_scope_1.createScopeMatcher; } });
158
+ Object.defineProperty(exports, "mergeSourceScope", { enumerable: true, get: function () { return source_scope_1.mergeSourceScope; } });
159
+ Object.defineProperty(exports, "normalizeScopePatterns", { enumerable: true, get: function () { return source_scope_1.normalizeScopePatterns; } });
160
+ Object.defineProperty(exports, "readSourceScope", { enumerable: true, get: function () { return source_scope_1.readSourceScope; } });
146
161
  // ── Local translation runner (CLI `babelize translate`, MCP `babelize_translate`) ──
147
162
  __exportStar(require("./local"), exports);
@@ -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,13 @@
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
+ import type { SourceScope } from '../utils/source-scope';
6
+ /** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
7
+ export declare function configRulesStore(glossary: LocaleGlossary | undefined, extra?: {
8
+ brandVoice?: string;
9
+ formality?: Record<string, FormalitySetting>;
10
+ }): ProjectRulesStore;
6
11
  import { type ByokProvider } from '@babelize/types';
7
12
  import type { HostedTranslationProvider } from './hosted-provider';
8
13
  import { type FormatResult } from './formatter';
@@ -32,6 +37,18 @@ export interface LocalTranslateOptions {
32
37
  * brought up to date (from the lockfile, so only new strings cost tokens).
33
38
  */
34
39
  replace?: boolean;
40
+ /**
41
+ * Form of address per target locale (or base language), e.g. `{ de: 'formal' }`
42
+ * (`--formality de=formal`). Merged over `.babelize/config.json` `formality`.
43
+ */
44
+ formality?: Record<string, FormalitySetting>;
45
+ /** Tone and style for the translator; replaces `.babelize/config.json` `brandVoice`. */
46
+ brandVoice?: string;
47
+ /**
48
+ * Source files to extract from and rewrite (`--include`/`--exclude` globs).
49
+ * Each list given replaces `.babelize/config.json` `include`/`exclude`.
50
+ */
51
+ sourceScope?: SourceScope;
35
52
  }
36
53
  export interface LocalTranslateDeps {
37
54
  /** 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,
@@ -353,6 +359,7 @@ async function runScoped(opts, deps, engineLog, state) {
353
359
  // and the updated one comes back with the other changes — only on success.
354
360
  dataDir: temp.dir,
355
361
  byok: translator ? undefined : opts.byok,
362
+ ...(opts.sourceScope ? { sourceScope: opts.sourceScope } : {}),
356
363
  providers: translator || rules ? { ...(translator ? { translator } : {}), ...(rules ? { rules } : {}) } : undefined,
357
364
  installDependencies: false,
358
365
  onProgress: (message, step, status) => deps.onProgress?.(message, step, status),
@@ -390,6 +397,18 @@ async function runScoped(opts, deps, engineLog, state) {
390
397
  if (locale.locale === opts.sourceLocale || locale.noFile)
391
398
  continue;
392
399
  const rel = locale.path.split(path.sep).join('/');
400
+ if (locale.files) {
401
+ // An adopted folder per locale (#370): each namespace file or module
402
+ // exactly as the engine produced it, existing translations kept.
403
+ for (const f of locale.files) {
404
+ const abs = path.resolve(temp.dir, f.path.split(path.sep).join('/'));
405
+ if (path.relative(temp.dir, abs).startsWith('..'))
406
+ continue;
407
+ await (0, promises_1.mkdir)(path.dirname(abs), { recursive: true });
408
+ await (0, promises_1.writeFile)(abs, f.content);
409
+ }
410
+ continue;
411
+ }
393
412
  if (locale.content !== undefined && !rel.endsWith('.json')) {
394
413
  // A merged catalogue (Django .po): written exactly as the engine
395
414
  // 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);
@@ -49,6 +49,7 @@ const jsx_message_1 = require("../../utils/jsx-message");
49
49
  const ui_copy_1 = require("../../utils/ui-copy");
50
50
  const module_constants_1 = require("../../utils/module-constants");
51
51
  const react_native_1 = require("../../utils/react-native");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  /** Frameworks whose injection strategies can render a JSX sentence as one message. */
53
54
  const SENTENCE_FRAMEWORKS = new Set(['react', 'nextjs', 'react-native']);
54
55
  async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
@@ -60,10 +61,8 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
60
61
  const notInjected = [];
61
62
  const sourceFiles = [];
62
63
  if (filesToProcess && filesToProcess.length > 0) {
63
- // If specific files are provided, only scan those
64
- for (const relPath of filesToProcess) {
65
- sourceFiles.push(path.join(workspace.path, relPath));
66
- }
64
+ // If specific files are provided, only scan those (still within the project's scope)
65
+ sourceFiles.push(...(0, source_scope_1.filterToScope)(workspace, filesToProcess.map((relPath) => path.join(workspace.path, relPath))));
67
66
  }
68
67
  else {
69
68
  // Otherwise scan all source directories. Root-scanning frameworks use
@@ -74,7 +73,7 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
74
73
  const excluded = (0, types_1.workspaceExcludes)(workspace);
75
74
  for (const sourceDir of workspace.sourceDirs) {
76
75
  const dirPath = path.join(workspace.path, sourceDir);
77
- const files = await (0, file_utils_1.findFiles)(dirPath, extensions, excluded);
76
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, excluded));
78
77
  sourceFiles.push(...files);
79
78
  }
80
79
  }
@@ -182,6 +181,20 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
182
181
  const isTypeScript = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
183
182
  try {
184
183
  const ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript });
184
+ // Options of this file's string-literal union types: never copy (#379).
185
+ const unionMembers = isTypeScript ? (0, ui_copy_1.literalUnionMembers)(ast) : new Set();
186
+ /**
187
+ * A string literal that picks a value rather than showing one: text
188
+ * direction, a union option, or a component prop option (#379).
189
+ */
190
+ const isOptionValue = (path, text) => {
191
+ if (!path.isStringLiteral?.())
192
+ return false;
193
+ if ((0, ui_copy_1.isDirectionValue)(text) || unionMembers.has(text))
194
+ return true;
195
+ const attribute = path.parentPath;
196
+ return !!attribute?.isJSXAttribute() && (0, ui_copy_1.isComponentOptionValue)(attribute.node, attribute.parentPath.node, text);
197
+ };
185
198
  // UI copy in module-level constants rendered by components (#248): keys
186
199
  // when every use is a render, otherwise reported — never silently skipped.
187
200
  if (!options?.framework || SENTENCE_FRAMEWORKS.has(options.framework)) {
@@ -240,6 +253,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
240
253
  return;
241
254
  if (/^\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?$/.test(text))
242
255
  return;
256
+ if (isOptionValue(path, text))
257
+ return;
243
258
  // A literal in a branch (`role === 'brand' ? 'brand' : 'creator'`, `user?.id ?? 'usr_1'`)
244
259
  // goes where the whole expression goes, so that's where it's judged.
245
260
  const site = valueSite(path);
@@ -465,6 +480,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
465
480
  return;
466
481
  if ((0, ast_helpers_1.isAlreadyTranslated)(path.node, path))
467
482
  return;
483
+ if (isOptionValue(path.get('value'), text))
484
+ return;
468
485
  const id = `${filePath}:${path.node.loc?.start.line}:${(0, string_utils_1.hashString)(text)}`;
469
486
  noteOffset(id, path.node.start);
470
487
  if (!seenTexts.has(id)) {
@@ -5,6 +5,12 @@ interface PackageJson {
5
5
  devDependencies?: Record<string, string>;
6
6
  [key: string]: unknown;
7
7
  }
8
+ /**
9
+ * Whether package.json describes a package published to npm (not an app):
10
+ * not private, with library entry points or a files list. `main` alone isn't
11
+ * enough: Expo, Electron and Node apps use it for their own entry.
12
+ */
13
+ export declare function isPublishedPackage(pkg: PackageJson): boolean;
8
14
  export declare function finalizeProject(workspace: WorkspaceInfo, dryRun: boolean, options?: {
9
15
  targetLocales?: string[];
10
16
  sourceLocale?: string;
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.isPublishedPackage = isPublishedPackage;
36
37
  exports.finalizeProject = finalizeProject;
37
38
  exports.i18nRuntimeFor = i18nRuntimeFor;
38
39
  const path = __importStar(require("path"));
@@ -49,6 +50,16 @@ const react_native_finalize_1 = require("./react-native-finalize");
49
50
  const dependencies_1 = require("./dependencies");
50
51
  const i18n_config_path_1 = require("../../utils/i18n-config-path");
51
52
  const i18next_icu_1 = require("../../utils/i18next-icu");
53
+ /**
54
+ * Whether package.json describes a package published to npm (not an app):
55
+ * not private, with library entry points or a files list. `main` alone isn't
56
+ * enough: Expo, Electron and Node apps use it for their own entry.
57
+ */
58
+ function isPublishedPackage(pkg) {
59
+ if (pkg.private === true)
60
+ return false;
61
+ return ['exports', 'module', 'types', 'typings', 'files', 'publishConfig'].some((field) => pkg[field] !== undefined);
62
+ }
52
63
  const DEPENDENCIES_BY_FRAMEWORK = {
53
64
  react: dependencies_1.I18NEXT_WEB_DEPENDENCIES,
54
65
  // Next.js projects that already use react-i18next keep it (injection picks
@@ -254,15 +265,22 @@ async function finalizeProject(workspace, dryRun, options = {}) {
254
265
  if (rn.warning)
255
266
  warnings.push(rn.warning);
256
267
  }
257
- const missingDeps = Object.keys(requiredDeps).filter((d) => !deps[d]);
268
+ // A package.json that is also a published library (a component kit with
269
+ // its docs site in the same package) would ship the site's i18n runtime
270
+ // to every consumer: it goes in devDependencies there (#378).
271
+ const field = isPublishedPackage(pkg) ? 'devDependencies' : 'dependencies';
272
+ const missingDeps = Object.keys(requiredDeps).filter((d) => !deps[d] && !(field === 'devDependencies' && pkg.devDependencies?.[d]));
258
273
  if (missingDeps.length > 0) {
259
- pkg.dependencies = pkg.dependencies || {};
274
+ const target = { ...pkg[field] };
260
275
  for (const dep of missingDeps) {
261
- pkg.dependencies[dep] = requiredDeps[dep];
276
+ target[dep] = requiredDeps[dep];
262
277
  }
263
278
  // Keep the user's key order (a sorted package.json is an unreviewable
264
279
  // diff); only the dependency map is sorted, as npm does.
265
- pkg.dependencies = Object.fromEntries(Object.entries(pkg.dependencies).sort(([a], [b]) => a.localeCompare(b)));
280
+ pkg[field] = Object.fromEntries(Object.entries(target).sort(([a], [b]) => a.localeCompare(b)));
281
+ if (field === 'devDependencies') {
282
+ warnings.push(`package.json is a published package, so ${missingDeps.join(', ')} went into devDependencies to keep ${missingDeps.length === 1 ? 'it' : 'them'} out of your consumers' installs.`);
283
+ }
266
284
  await writer.write(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
267
285
  if (!dryRun) {
268
286
  // A committed lockfile must move with package.json, or `npm ci` /
@@ -745,5 +763,7 @@ function i18nRuntimeFor(framework, pkg) {
745
763
  : fw === 'react-native' ? (0, react_native_finalize_1.reactNativeDependencies)(pkg ?? undefined).deps
746
764
  : DEPENDENCIES_BY_FRAMEWORK[fw] ?? {});
747
765
  const library = nextIntl ? 'next-intl' : fw === 'vue' ? 'vue-i18n' : 'react-i18next';
748
- return { library, required, missing: required.filter((d) => !(pkg?.dependencies ?? {})[d]) };
766
+ // A published package keeps them in devDependencies (see finalizeWorkspace).
767
+ const installed = pkg && isPublishedPackage(pkg) ? deps : pkg?.dependencies ?? {};
768
+ return { library, required, missing: required.filter((d) => !installed[d]) };
749
769
  }
@@ -6,32 +6,89 @@ import type { WorkspaceInfo } from '../../runtime/types';
6
6
  * Injection rewrites Next.js components to next-intl (`getTranslations` in
7
7
  * Server Components, `useTranslations` in Client Components — see
8
8
  * NextIntlStrategy), so the project must be wired for next-intl or every
9
- * page throws at runtime. This sets up next-intl's "without i18n routing"
10
- * mode: the locale comes from a NEXT_LOCALE cookie or the browser's
11
- * Accept-Language header, and messages are the generated
12
- * `public/locales/<locale>.json` files. URLs don't change.
9
+ * page throws at runtime. Each language gets its own URL without moving any
10
+ * route (#380): a generated proxy (middleware before Next 16) serves
11
+ * `/ja/docs` from the existing `app/docs` route and tells next-intl the
12
+ * locale in a request header. The source language stays unprefixed, a
13
+ * NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
14
+ * its translations to search engines with hreflang `Link` headers. The root
15
+ * layout's <html> gets the locale's `lang` and `dir`. Messages are the
16
+ * generated `public/locales/<locale>.json` files.
17
+ *
18
+ * `"routing": "cookie"` in .babelize/config.json keeps one URL for every
19
+ * language (the locale comes from the cookie or Accept-Language).
13
20
  *
14
21
  * Every edit is a minimal text splice (the user's formatting is kept), and
15
22
  * anything that can't be wired automatically becomes a warning — never a
16
23
  * silently half-configured project.
17
24
  */
18
25
  export declare const NEXT_INTL_DEPENDENCIES: Record<string, string>;
26
+ /** Request header the proxy sets with the URL's locale. */
27
+ export declare const LOCALE_HEADER = "x-babelize-locale";
28
+ export type NextRouting = 'prefix' | 'cookie';
19
29
  export interface NextIntlFinalizeResult {
20
30
  configFileCreated: boolean;
21
31
  entryPointModified: boolean;
22
32
  warnings: string[];
23
33
  }
34
+ /**
35
+ * `i18n/locales`: the locale list and text direction, shared by the request
36
+ * config, the proxy and the root layout. Plain data, safe to import anywhere.
37
+ */
38
+ export declare function buildLocalesModule(opts: {
39
+ sourceLocale: string;
40
+ locales: string[];
41
+ typescript: boolean;
42
+ }): string;
24
43
  export declare function buildRequestConfig(opts: {
25
44
  sourceLocale: string;
26
45
  locales: string[];
27
46
  /** Import path from the request config file to a locale file, with `__LOCALE__` as placeholder. */
28
47
  messagesImportPath: string;
29
48
  typescript: boolean;
49
+ /** `prefix`: the proxy's locale header wins. Default `cookie` (no proxy). */
50
+ routing?: NextRouting;
51
+ }): string;
52
+ /**
53
+ * The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
54
+ * locale in a request header; the source language has no prefix. A visitor
55
+ * who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
56
+ * lists its translations in hreflang `Link` headers.
57
+ */
58
+ export declare function buildProxy(opts: {
59
+ kind: 'proxy' | 'middleware';
60
+ typescript: boolean;
30
61
  }): string;
62
+ /**
63
+ * Give the root layout's <html> the active locale's `lang` and `dir`
64
+ * (#380): `const locale = useLocale()` in the default-exported layout
65
+ * (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
66
+ * can edit safely (no <html>, an expression-bodied arrow, no default export).
67
+ */
68
+ export declare function setHtmlLocale(content: string, typescript: boolean, localesImport: string): string | null;
69
+ /** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
70
+ export declare function nextMajor(packageJson: Record<string, any> | undefined): number | null;
31
71
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
32
72
  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;
73
+ /**
74
+ * True when next.config turns on Cache Components (`cacheComponents: true`,
75
+ * the default in create-next-app 16.4+, or `experimental.dynamicIO` before
76
+ * Next 16). Then request data — the cookies and headers our request config
77
+ * reads — may only be read inside <Suspense>, or `next build` fails with
78
+ * "Next.js encountered uncached or runtime data during prerendering".
79
+ */
80
+ export declare function usesCacheComponents(nextConfig: string): boolean;
81
+ /**
82
+ * Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
83
+ *
84
+ * With `suspense` (Cache Components on), the whole <body> content is wrapped
85
+ * in <Suspense><NextIntlClientProvider>…, so every translated component —
86
+ * including a header or footer rendered by the layout itself — reads the
87
+ * locale inside a Suspense boundary.
88
+ */
89
+ export declare function wrapRootLayout(content: string, typescript: boolean, options?: {
90
+ suspense?: boolean;
91
+ }): string | null;
35
92
  export declare function finalizeNextIntl(workspace: WorkspaceInfo, dryRun: boolean, options: {
36
93
  sourceLocale?: string;
37
94
  targetLocales?: string[];