@babelize/engine 0.3.15 → 0.3.17

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.
@@ -36,6 +36,8 @@ export interface RepoFiles {
36
36
  size?(relPath: string): number | undefined;
37
37
  }
38
38
  export declare const FRAMEWORK_DISPLAY_NAMES: Record<string, string>;
39
+ /** How deep a JS app's package.json may be (apps/web/package.json is 2). Shared with findWorkspaceApp. */
40
+ export declare const MAX_APP_DEPTH = 3;
39
41
  /** Does a Python dependency file list Django itself (not just django-* add-ons)? */
40
42
  export declare function mentionsPythonPackage(content: string, pkg: string): boolean;
41
43
  /** Human list of supported stacks, for messages. */
@@ -47,7 +47,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
47
47
  return (mod && mod.__esModule) ? mod : { "default": mod };
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
- exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = void 0;
50
+ exports.SUPPORTED_SUMMARY = exports.MAX_APP_DEPTH = exports.FRAMEWORK_DISPLAY_NAMES = void 0;
51
51
  exports.mentionsPythonPackage = mentionsPythonPackage;
52
52
  exports.detectPackageManagers = detectPackageManagers;
53
53
  exports.detectStack = detectStack;
@@ -60,6 +60,8 @@ exports.FRAMEWORK_DISPLAY_NAMES = {
60
60
  'react-native': 'React Native', unknown: 'Unknown',
61
61
  };
62
62
  const IGNORED_DIR = /(?:^|\/)(?:node_modules|\.git|venv|\.venv|env|site-packages|vendor|dist|build|\.next|__pycache__)\//;
63
+ /** How deep a JS app's package.json may be (apps/web/package.json is 2). Shared with findWorkspaceApp. */
64
+ exports.MAX_APP_DEPTH = 3;
63
65
  function depth(p) {
64
66
  return p.split('/').length - 1;
65
67
  }
@@ -176,8 +178,13 @@ async function detectStack(files) {
176
178
  const managePy = paths.filter((p) => p.endsWith('/manage.py') && depth(p) <= 3).sort((a, b) => depth(a) - depth(b));
177
179
  if (managePy.length > 0 || mentionsPythonPackage(pyDeps, 'django'))
178
180
  return result('django', true);
179
- // 4. A JS framework in a workspace package or first-level subdirectory.
180
- const subPkgs = paths.filter((p) => p.endsWith('/package.json') && depth(p) <= 2).slice(0, 25);
181
+ // 4. A JS framework in a subdirectory, up to three levels down (apps/web,
182
+ // frontend/apps/web), nearest first: the same places findWorkspaceApp looks
183
+ // when the run starts, so a repo that passes here can be babelized.
184
+ const subPkgs = paths
185
+ .filter((p) => p.endsWith('/package.json') && depth(p) <= exports.MAX_APP_DEPTH)
186
+ .sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
187
+ .slice(0, 40);
181
188
  for (const p of subPkgs) {
182
189
  const sub = jsFramework(await readJson(files, p));
183
190
  if (SUPPORTED_JS.has(sub.id))
@@ -323,6 +323,10 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
323
323
  }
324
324
  let parent = path.parentPath;
325
325
  while (parent) {
326
+ // A string inside a handler (`onPress={() => Alert.alert('Saved')}`) belongs to the
327
+ // function, not to the attribute holding it: onPress isn't copy, but the alert is.
328
+ if (parent.isFunction())
329
+ break;
326
330
  if (parent.isJSXAttribute()) {
327
331
  const nameNode = parent.node.name;
328
332
  if (ast_helpers_1.t.isJSXIdentifier(nameNode) &&
@@ -1,5 +1,11 @@
1
1
  import type { WorkspaceInfo } from '../../runtime/types';
2
2
  import { FinalizationWriter } from './writes';
3
+ /**
4
+ * Hermes, React Native's JavaScript engine, has no Intl.PluralRules. Without
5
+ * it intl-messageformat can't format a plural, and i18next-icu shows the raw
6
+ * message (`{count, plural, one {…} other {…}}`) instead.
7
+ */
8
+ export declare const PLURAL_POLYFILL_DEPENDENCIES: Record<string, string>;
3
9
  interface PackageJson {
4
10
  main?: string;
5
11
  dependencies?: Record<string, 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.PLURAL_POLYFILL_DEPENDENCIES = void 0;
36
37
  exports.isExpoProject = isExpoProject;
37
38
  exports.expoSdkMajor = expoSdkMajor;
38
39
  exports.expoLocalizationFor = expoLocalizationFor;
@@ -76,6 +77,16 @@ const EXPO_LOCALIZATION_BY_SDK = {
76
77
  };
77
78
  const FIRST_SDK_WITH_MATCHING_MAJORS = 55;
78
79
  const REACT_NATIVE_LOCALIZE = '^3.7.2';
80
+ /**
81
+ * Hermes, React Native's JavaScript engine, has no Intl.PluralRules. Without
82
+ * it intl-messageformat can't format a plural, and i18next-icu shows the raw
83
+ * message (`{count, plural, one {…} other {…}}`) instead.
84
+ */
85
+ exports.PLURAL_POLYFILL_DEPENDENCIES = {
86
+ '@formatjs/intl-getcanonicallocales': '^3.4.2',
87
+ '@formatjs/intl-locale': '^5.5.2',
88
+ '@formatjs/intl-pluralrules': '^7.1.2',
89
+ };
79
90
  function allDeps(pkg) {
80
91
  return { ...pkg?.dependencies, ...pkg?.devDependencies };
81
92
  }
@@ -98,7 +109,7 @@ function expoLocalizationFor(expoRange) {
98
109
  }
99
110
  /** Dependencies a React Native app needs, and a warning when a version is a guess. */
100
111
  function reactNativeDependencies(pkg) {
101
- const deps = { ...dependencies_1.I18NEXT_CORE_DEPENDENCIES };
112
+ const deps = { ...dependencies_1.I18NEXT_CORE_DEPENDENCIES, ...exports.PLURAL_POLYFILL_DEPENDENCIES };
102
113
  if (!isExpoProject(pkg)) {
103
114
  deps['react-native-localize'] = REACT_NATIVE_LOCALIZE;
104
115
  return { deps };
@@ -129,6 +140,29 @@ function messagesIdentifier(locale) {
129
140
  return `${/^[0-9]/.test(camel) ? `_${camel}` : camel}Messages`;
130
141
  }
131
142
  const LOCALES_INDEX_MARKER = '// @babelize-generated locale index';
143
+ /**
144
+ * The Intl.PluralRules polyfill and the plural rules of each bundled language
145
+ * (by language: `pt-BR` uses `pt`). In the index, which is rewritten every
146
+ * run, so a language added later gets its rules too.
147
+ *
148
+ * Required only where the API is missing (Hermes), not imported: the
149
+ * FormatJS packages are ESM-only, and Node-based tests (jest-expo doesn't
150
+ * transform node_modules) fail to parse them. Node has Intl.PluralRules, so
151
+ * there they are never loaded; Metro bundles them for the app.
152
+ */
153
+ function pluralPolyfill(locales) {
154
+ const languages = [...new Set(locales.map((l) => l.split(/[-_]/)[0].toLowerCase()))];
155
+ return [
156
+ '// Hermes has no Intl.PluralRules: without it plurals render as raw ICU text.',
157
+ "if (typeof Intl.PluralRules === 'undefined') {",
158
+ " require('@formatjs/intl-getcanonicallocales/polyfill.js');",
159
+ " require('@formatjs/intl-locale/polyfill.js');",
160
+ " require('@formatjs/intl-pluralrules/polyfill.js');",
161
+ ...languages.map((l) => ` require('@formatjs/intl-pluralrules/locale-data/${l}.js');`),
162
+ '}',
163
+ '',
164
+ ];
165
+ }
132
166
  /** `<locales>/index.(ts|js)`: every bundled locale, source first. */
133
167
  function buildLocalesIndex(locales, sourceLocale) {
134
168
  const ordered = [sourceLocale, ...locales.filter((l) => l !== sourceLocale).sort()];
@@ -138,6 +172,7 @@ function buildLocalesIndex(locales, sourceLocale) {
138
172
  `${LOCALES_INDEX_MARKER}: rewritten by Babelize on every run, edit the JSON files instead.`,
139
173
  ...imports,
140
174
  '',
175
+ ...pluralPolyfill(ordered),
141
176
  'export const resources = {',
142
177
  ...entries,
143
178
  '};',
@@ -274,7 +309,8 @@ async function finalizeReactNative(workspace, options, writer) {
274
309
  warnings.push(note);
275
310
  if (icu.userOwnsInit) {
276
311
  warnings.push(`This app sets up i18next itself, so Babelize didn't add an i18n config. ` +
277
- `Add the bundled translations (\`import { resources } from './${path.posix.relative(configDir, localesRel) || '.'}'\`) to your i18next.init().`);
312
+ `Add the bundled translations (\`import { resources } from './${path.posix.relative(configDir, localesRel) || '.'}'\`) to your i18next.init(). ` +
313
+ `Importing that file also loads the Intl.PluralRules polyfill Hermes needs for plurals.`);
278
314
  return { configFileCreated, entryPointModified, userOwnsInit: true, warnings };
279
315
  }
280
316
  // i18n config: written once, next to the locales.
@@ -0,0 +1,15 @@
1
+ import type { GlossaryRules } from './rules';
2
+ /**
3
+ * The app's own name, kept as written in every language (NLLB turned
4
+ * "Tasklane" into "pour les enfants"). Read from the project, never guessed
5
+ * from the strings:
6
+ *
7
+ * - an explicit app name (Expo `app.json` `expo.name`, a web manifest
8
+ * `name`/`short_name`) counts on its own;
9
+ * - the start of the page title ("Tasklane: the to-do list…", `metadata.title`
10
+ * or `<title>`) counts only when `package.json`'s name agrees, so a title
11
+ * like "Dashboard | Acme" can't put "Dashboard" on the never-translate list.
12
+ */
13
+ export declare function detectBrandNames(workspacePath: string): string[];
14
+ /** `glossary` with the brand names added to its never-translate terms (unless the glossary already rules on them). */
15
+ export declare function withBrandNames(glossary: GlossaryRules, brandNames: readonly string[]): GlossaryRules;
@@ -0,0 +1,147 @@
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
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.detectBrandNames = detectBrandNames;
37
+ exports.withBrandNames = withBrandNames;
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ /**
41
+ * The app's own name, kept as written in every language (NLLB turned
42
+ * "Tasklane" into "pour les enfants"). Read from the project, never guessed
43
+ * from the strings:
44
+ *
45
+ * - an explicit app name (Expo `app.json` `expo.name`, a web manifest
46
+ * `name`/`short_name`) counts on its own;
47
+ * - the start of the page title ("Tasklane: the to-do list…", `metadata.title`
48
+ * or `<title>`) counts only when `package.json`'s name agrees, so a title
49
+ * like "Dashboard | Acme" can't put "Dashboard" on the never-translate list.
50
+ */
51
+ function detectBrandNames(workspacePath) {
52
+ const names = new Set();
53
+ for (const name of explicitAppNames(workspacePath))
54
+ names.add(name);
55
+ const packageName = readJson(path.join(workspacePath, 'package.json'))?.name;
56
+ const packageWords = typeof packageName === 'string' ? nameWords(packageName.replace(/^@[^/]+\//, '')) : [];
57
+ const title = pageTitle(workspacePath);
58
+ const titleName = title ? titlePrefix(title) : null;
59
+ if (titleName && packageWords.length > 0 && packageAgrees(titleName, packageWords))
60
+ names.add(titleName);
61
+ return [...names];
62
+ }
63
+ /** `glossary` with the brand names added to its never-translate terms (unless the glossary already rules on them). */
64
+ function withBrandNames(glossary, brandNames) {
65
+ const ruled = new Set([...glossary.neverTranslate, ...glossary.alwaysTranslateAs.map((e) => e.term)].map((t) => t.toLowerCase()));
66
+ const added = brandNames.filter((name) => !ruled.has(name.toLowerCase()));
67
+ return added.length === 0 ? glossary : { ...glossary, neverTranslate: [...glossary.neverTranslate, ...added] };
68
+ }
69
+ const MAX_BRAND_LENGTH = 40;
70
+ function explicitAppNames(root) {
71
+ const found = [];
72
+ const expo = readJson(path.join(root, 'app.json'))?.expo;
73
+ if (expo && typeof expo === 'object')
74
+ found.push(expo.name);
75
+ for (const file of ['public/manifest.json', 'public/site.webmanifest', 'public/manifest.webmanifest', 'app/manifest.json']) {
76
+ const manifest = readJson(path.join(root, file));
77
+ if (manifest)
78
+ found.push(manifest.short_name, manifest.name);
79
+ }
80
+ return found.filter(isBrandLike).map((name) => name.trim());
81
+ }
82
+ /** The page title: Next `metadata.title` (string or `default`) in the root layout, else an HTML `<title>`. */
83
+ function pageTitle(root) {
84
+ for (const dir of ['app', 'src/app']) {
85
+ for (const ext of ['tsx', 'ts', 'jsx', 'js']) {
86
+ const source = readText(path.join(root, dir, `layout.${ext}`));
87
+ const match = source?.match(/\btitle\s*:\s*(?:\{[^}]*?\bdefault\s*:\s*)?(["'`])([^"'`\n]+)\1/);
88
+ if (match)
89
+ return match[2];
90
+ }
91
+ }
92
+ for (const file of ['index.html', 'public/index.html']) {
93
+ const match = readText(path.join(root, file))?.match(/<title>([^<]+)<\/title>/i);
94
+ if (match)
95
+ return match[1];
96
+ }
97
+ return null;
98
+ }
99
+ /** "Tasklane: the to-do list" → "Tasklane"; a title with no separator is the name only if it's short. */
100
+ function titlePrefix(title) {
101
+ const parts = title.split(/\s*(?::|\||—|–|·|\s-\s)\s*/);
102
+ const head = parts[0].trim();
103
+ if (parts.length === 1 && head.split(/\s+/).length > 2)
104
+ return null;
105
+ return isBrandLike(head) ? head : null;
106
+ }
107
+ /** "tasklane-sample" agrees with "Tasklane"; "my-web-app" agrees with nothing. */
108
+ function packageAgrees(name, packageWords) {
109
+ const compact = name.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');
110
+ if (compact.length < 3)
111
+ return false;
112
+ const words = packageWords.filter((w) => !GENERIC_PACKAGE_WORDS.has(w));
113
+ return words.includes(compact) || words.join('') === compact;
114
+ }
115
+ const GENERIC_PACKAGE_WORDS = new Set([
116
+ 'app', 'apps', 'web', 'www', 'site', 'website', 'frontend', 'client', 'ui', 'sample', 'example', 'demo',
117
+ 'starter', 'template', 'my', 'next', 'nextjs', 'react', 'vue', 'vite', 'landing', 'page', 'dashboard',
118
+ ]);
119
+ function nameWords(name) {
120
+ return name.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
121
+ }
122
+ function isBrandLike(value) {
123
+ if (typeof value !== 'string')
124
+ return false;
125
+ const v = value.trim();
126
+ return v.length >= 2 && v.length <= MAX_BRAND_LENGTH && /\p{L}/u.test(v) && v.split(/\s+/).length <= 3;
127
+ }
128
+ function readText(file) {
129
+ try {
130
+ return fs.readFileSync(file, 'utf8');
131
+ }
132
+ catch {
133
+ return null;
134
+ }
135
+ }
136
+ function readJson(file) {
137
+ const text = readText(file);
138
+ if (!text)
139
+ return null;
140
+ try {
141
+ const value = JSON.parse(text);
142
+ return value && typeof value === 'object' ? value : null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
@@ -1,9 +1,5 @@
1
1
  import type { LockfileEntry } from './schema';
2
2
  import { type LockfileData, type LockfilePartition, type LockfileStats, type PartitionedKey } from './schema';
3
- /**
4
- * For each target locale, list of translation keys that must go through the translator
5
- * (new keys, source-changed keys, or keys missing that locale in the lockfile).
6
- */
7
3
  export declare function buildKeysToTranslateByTargetLocale(partition: LockfilePartition, targetLocales: string[]): Record<string, string[]>;
8
4
  /**
9
5
  * Resolve the lockfile path for a project:
@@ -53,6 +53,7 @@ const pseudo_markers_1 = require("../../utils/pseudo-markers");
53
53
  const fs = __importStar(require("fs-extra"));
54
54
  const logger_1 = require("../../utils/logger");
55
55
  const hasher_1 = require("./hasher");
56
+ const untranslated_1 = require("../../utils/untranslated");
56
57
  const schema_1 = require("./schema");
57
58
  const LOCK_RETRIES = 20;
58
59
  const LOCK_RETRY_DELAY_MS = 50;
@@ -84,6 +85,10 @@ async function releaseLock(lockDir) {
84
85
  * For each target locale, list of translation keys that must go through the translator
85
86
  * (new keys, source-changed keys, or keys missing that locale in the lockfile).
86
87
  */
88
+ /** Words of two or more letters, ignoring placeholders. */
89
+ function wordCount(text) {
90
+ return text.replace(/\{[^{}]*\}/g, ' ').split(/\s+/).filter((w) => /\p{L}{2,}/u.test(w)).length;
91
+ }
87
92
  function buildKeysToTranslateByTargetLocale(partition, targetLocales) {
88
93
  const byLocale = {};
89
94
  for (const loc of targetLocales) {
@@ -473,12 +478,14 @@ function updateLockfile(lockfile, keys, translations, projectId, metadata) {
473
478
  // Merge per-locale translations and metadata
474
479
  for (const [locale, translatedKeys] of Object.entries(translations)) {
475
480
  if (translatedKeys[key]) {
476
- // Skip caching identity translations (same as source text) for non-trivial strings.
477
- // Identity translations mean the translator fell back to source text
478
- // (e.g., because the service was unavailable). Caching them would cause
479
- // subsequent runs to skip re-translation and produce fake locale files.
481
+ // Skip caching a translation that is the source text where that can't be
482
+ // right: a sentence of 3+ words, or words left in Latin script for a
483
+ // non-Latin language. Those mean the translator fell back to the source,
484
+ // and caching them would skip re-translation on every later run. A word
485
+ // that is the same in both languages ("Version" in French, "API" in
486
+ // Japanese) is cached, so it isn't re-translated and re-charged every run.
480
487
  const translated = translatedKeys[key];
481
- if (translated === value && value.length > 4) {
488
+ if (translated === value && (wordCount(value) >= 3 || (0, untranslated_1.isUntranslatedInto)(value, translated, locale))) {
482
489
  logger_1.engineLogger.warn(`Skipping cache for "${key}" → "${locale}": identity translation (same as source). Translator may be unavailable.`);
483
490
  continue;
484
491
  }
@@ -27,6 +27,12 @@ interface PromptEntry {
27
27
  }
28
28
  export declare class BYOKTranslatorClient implements TranslatorClient {
29
29
  private readonly config;
30
+ /**
31
+ * Shared by every request this client makes (a run's batches and locales go
32
+ * out concurrently): one 429 pauses them all until the quota resets, instead
33
+ * of each one spending its retries against the same limit.
34
+ */
35
+ private rateLimitedUntil;
30
36
  constructor(config: BYOKProviderConfig);
31
37
  health(): Promise<boolean>;
32
38
  warmup(): Promise<boolean>;
@@ -37,6 +43,7 @@ export declare class BYOKTranslatorClient implements TranslatorClient {
37
43
  /** Anthropic: force a tool call so the output is schema-shaped JSON. */
38
44
  private callAnthropic;
39
45
  private callOpenAICompatible;
46
+ private waitForQuota;
40
47
  private httpError;
41
48
  private formatApiError;
42
49
  private redactApiKey;
@@ -21,10 +21,19 @@ const formality_1 = require("../formality");
21
21
  const icu_message_1 = require("../../../utils/icu-message");
22
22
  // Rough character to token ratio
23
23
  const CHAR_TO_TOKEN_RATIO = 4;
24
- const RETRY = { baseDelayMs: 1000, maxRetries: 3, timeoutMs: 120000 };
24
+ const RETRY = { baseDelayMs: 1000, maxRetries: 3, rateLimitRetries: 6, timeoutMs: 120000 };
25
+ /** Pause after a 429 that names no wait of its own. */
26
+ const DEFAULT_RATE_LIMIT_PAUSE_MS = 15000;
27
+ const MAX_RATE_LIMIT_PAUSE_MS = 60000;
25
28
  const TOOL_NAME = 'submit_translations';
26
29
  class BYOKTranslatorClient {
27
30
  constructor(config) {
31
+ /**
32
+ * Shared by every request this client makes (a run's batches and locales go
33
+ * out concurrently): one 429 pauses them all until the quota resets, instead
34
+ * of each one spending its retries against the same limit.
35
+ */
36
+ this.rateLimitedUntil = 0;
28
37
  this.config = config;
29
38
  }
30
39
  async health() {
@@ -101,6 +110,7 @@ class BYOKTranslatorClient {
101
110
  /** Anthropic: force a tool call so the output is schema-shaped JSON. */
102
111
  async callAnthropic(model, system, user, retry = RETRY) {
103
112
  const response = await (0, retry_1.withRetry)(async (signal) => {
113
+ await this.waitForQuota(signal);
104
114
  const res = await fetch(this.getBaseUrl(), {
105
115
  method: 'POST',
106
116
  headers: {
@@ -159,6 +169,7 @@ class BYOKTranslatorClient {
159
169
  body.response_format = { type: 'json_object' };
160
170
  }
161
171
  const response = await (0, retry_1.withRetry)(async (signal) => {
172
+ await this.waitForQuota(signal);
162
173
  const res = await fetch(this.getBaseUrl(), {
163
174
  method: 'POST',
164
175
  headers: {
@@ -174,9 +185,19 @@ class BYOKTranslatorClient {
174
185
  }, retry);
175
186
  return { content: response.choices?.[0]?.message?.content ?? '', usage: response.usage };
176
187
  }
188
+ async waitForQuota(signal) {
189
+ const wait = this.rateLimitedUntil - Date.now();
190
+ if (wait > 0)
191
+ await (0, retry_1.sleep)(wait, signal);
192
+ }
177
193
  async httpError(res) {
178
- const detail = this.redactApiKey((await res.text().catch(() => '')).slice(0, 300));
179
- return new retry_1.ProviderHttpError(this.formatApiError(res.status, detail), res.status, (0, retry_1.parseRetryAfter)(res.headers.get('retry-after')));
194
+ const body = await res.text().catch(() => '');
195
+ const detail = this.redactApiKey(body.slice(0, 300));
196
+ const retryAfter = (0, retry_1.parseRetryAfter)(res.headers.get('retry-after')) ?? (0, retry_1.parseRetryDelayBody)(body);
197
+ if (res.status === 429) {
198
+ this.rateLimitedUntil = Math.max(this.rateLimitedUntil, Date.now() + Math.min(retryAfter ?? DEFAULT_RATE_LIMIT_PAUSE_MS, MAX_RATE_LIMIT_PAUSE_MS));
199
+ }
200
+ return new retry_1.ProviderHttpError(this.formatApiError(res.status, detail), res.status, retryAfter);
180
201
  }
181
202
  formatApiError(status, detail) {
182
203
  const name = this.getProviderDisplayName();
@@ -4,9 +4,15 @@ export interface RetryOptions {
4
4
  timeoutMs: number;
5
5
  /** Upper bound for a single wait, including server-requested Retry-After. */
6
6
  maxDelayMs?: number;
7
+ /**
8
+ * Retries for a 429, counted apart from maxRetries: a per-minute quota needs
9
+ * waits that add up to a minute or more (default maxRetries).
10
+ */
11
+ rateLimitRetries?: number;
7
12
  /** Aborts the attempt in flight and stops any further retries. */
8
13
  signal?: AbortSignal;
9
14
  }
15
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
10
16
  /** An HTTP error from a translation API, carrying what retry decisions need. */
11
17
  export declare class ProviderHttpError extends Error {
12
18
  readonly status: number;
@@ -16,6 +22,11 @@ export declare class ProviderHttpError extends Error {
16
22
  /** Server-requested wait from a Retry-After header, in ms. */
17
23
  retryAfterMs?: number | undefined);
18
24
  }
25
+ /**
26
+ * The wait Gemini asks for in a 429's body (`"retryDelay": "37s"` in its
27
+ * RetryInfo detail), which it sends instead of a Retry-After header.
28
+ */
29
+ export declare function parseRetryDelayBody(body: string): number | undefined;
19
30
  /** Parse a Retry-After header (seconds or HTTP date) into milliseconds. */
20
31
  export declare function parseRetryAfter(header: string | null): number | undefined;
21
32
  /**
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.withRetry503 = exports.ProviderHttpError = void 0;
4
+ exports.sleep = sleep;
5
+ exports.parseRetryDelayBody = parseRetryDelayBody;
4
6
  exports.parseRetryAfter = parseRetryAfter;
5
7
  exports.isRetryable = isRetryable;
6
8
  exports.withRetry = withRetry;
@@ -36,6 +38,14 @@ class ProviderHttpError extends Error {
36
38
  }
37
39
  }
38
40
  exports.ProviderHttpError = ProviderHttpError;
41
+ /**
42
+ * The wait Gemini asks for in a 429's body (`"retryDelay": "37s"` in its
43
+ * RetryInfo detail), which it sends instead of a Retry-After header.
44
+ */
45
+ function parseRetryDelayBody(body) {
46
+ const match = /"retryDelay"\s*:\s*"(\d+(?:\.\d+)?)s"/.exec(body);
47
+ return match ? Math.ceil(Number(match[1]) * 1000) : undefined;
48
+ }
39
49
  /** Parse a Retry-After header (seconds or HTTP date) into milliseconds. */
40
50
  function parseRetryAfter(header) {
41
51
  if (!header)
@@ -61,7 +71,9 @@ function isRetryable(err) {
61
71
  }
62
72
  async function withRetry(fn, opts) {
63
73
  const maxDelay = opts.maxDelayMs ?? 60000;
74
+ const rateLimitRetries = opts.rateLimitRetries ?? opts.maxRetries;
64
75
  let attempt = 0;
76
+ let rateLimited = 0;
65
77
  const outer = opts.signal;
66
78
  while (true) {
67
79
  if (outer?.aborted)
@@ -76,10 +88,14 @@ async function withRetry(fn, opts) {
76
88
  catch (err) {
77
89
  if (outer?.aborted)
78
90
  throw abortError();
79
- attempt += 1;
80
- if (attempt > opts.maxRetries || !isRetryable(err))
91
+ const is429 = err instanceof ProviderHttpError && err.status === 429;
92
+ if (is429)
93
+ rateLimited += 1;
94
+ else
95
+ attempt += 1;
96
+ if (!isRetryable(err) || attempt > opts.maxRetries || rateLimited > rateLimitRetries)
81
97
  throw err;
82
- const backoff = opts.baseDelayMs * Math.pow(2, attempt - 1);
98
+ const backoff = opts.baseDelayMs * Math.pow(2, (is429 ? rateLimited : attempt) - 1);
83
99
  const requested = err instanceof ProviderHttpError ? err.retryAfterMs : undefined;
84
100
  const delay = Math.min(maxDelay, Math.max(backoff, requested ?? 0));
85
101
  await sleep(delay, outer);
@@ -19,6 +19,7 @@ const concurrent_map_1 = require("../../utils/concurrent-map");
19
19
  const endonyms_1 = require("../../utils/endonyms");
20
20
  const language_codes_1 = require("./language-codes");
21
21
  const glossary_1 = require("../glossary");
22
+ const brand_1 = require("../glossary/brand");
22
23
  const check_project_1 = require("../../qa/check-project");
23
24
  const gemini_provider_1 = require("./client/gemini.provider");
24
25
  const memory_matcher_1 = require("./memory/memory-matcher");
@@ -34,6 +35,8 @@ const BATCH_SIZE = 15;
34
35
  exports.FALLBACK_QA_WARNING = 'translated with the backup translator; will be retried with the AI translator next run';
35
36
  /** Keys re-sent after failing validation go in small batches with per-key notes. */
36
37
  const REPAIR_BATCH_SIZE = 5;
38
+ /** Consecutive fallback batches that translate nothing before the fallback is given up on for a locale. */
39
+ const FALLBACK_MAX_EMPTY_BATCHES = 2;
37
40
  const TRANSLATE_CONCURRENCY = 3; // Max concurrent locales/batches
38
41
  /** Fragments of placeholder tokens ([#VAR_0#], the translator's {#0}) left in a translation. */
39
42
  const PLACEHOLDER_DEBRIS = /\[#|#\]|\[\{#|\{#\d+\}|#VAR_\d+/;
@@ -288,7 +291,11 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
288
291
  ?? (projectId
289
292
  ? await loadProjectTranslationRules(projectId, providers.rules)
290
293
  : await loadWorkspaceRules(workspace.path));
291
- const glossary = rules.glossary;
294
+ // The app's own name joins the never-translate terms for this run.
295
+ const brandNames = (0, brand_1.detectBrandNames)(workspace.path);
296
+ if (brandNames.length > 0)
297
+ logger_1.engineLogger.info('Keeping the app name as written', { brandNames });
298
+ const glossary = (0, brand_1.withBrandNames)(rules.glossary, brandNames);
292
299
  const neverTranslateTerms = glossary.neverTranslate;
293
300
  const brandVoice = rules.brandVoice;
294
301
  const rulesComplete = rules.complete;
@@ -997,7 +1004,15 @@ configuredFormality) {
997
1004
  }).map((b) => (b.plain ? { ...b, ...b.plain, icu: false, countArgs: undefined, plain: undefined } : b));
998
1005
  if (toFallback.length > 0) {
999
1006
  logger_1.engineLogger.warn('LLM translator unavailable; trying the fallback translator', { count: toFallback.length, targetLang });
1007
+ // A fallback that is down fails every batch after a timeout: stop after
1008
+ // two empty batches in a row (the keys stay failed and the next run retries them).
1009
+ let emptyBatches = 0;
1000
1010
  for (const batch of chunk(toFallback, BATCH_SIZE)) {
1011
+ if (emptyBatches >= FALLBACK_MAX_EMPTY_BATCHES) {
1012
+ logger_1.engineLogger.warn('Fallback translator is not producing translations; skipping the rest for this locale', { targetLang });
1013
+ break;
1014
+ }
1015
+ const before = fellBack.size;
1001
1016
  try {
1002
1017
  const keyResults = await fallback.translateBatch({
1003
1018
  entries: batch.map((b) => ({ key: b.key, value: b.sendText, parentContext: contextMap?.[b.key] })),
@@ -1017,6 +1032,7 @@ configuredFormality) {
1017
1032
  catch (error) {
1018
1033
  logger_1.engineLogger.error('Fallback translation batch failed', { error: error instanceof Error ? error.message : String(error), targetLang });
1019
1034
  }
1035
+ emptyBatches = fellBack.size > before ? 0 : emptyBatches + 1;
1020
1036
  }
1021
1037
  }
1022
1038
  const icuToFallback = prepared.filter((b) => {
@@ -341,6 +341,19 @@ async function findWorkspaceApp(workspacePath, rootPackageJson) {
341
341
  if (await (0, file_utils_1.isDirectory)(dir))
342
342
  candidates.push(dir);
343
343
  }
344
+ // Without a workspaces field: apps deeper down (apps/web, frontend/apps/web),
345
+ // nearest first, as far as detectStack looks before the project is created.
346
+ const nested = await (0, fast_glob_1.default)(['*/*/package.json', '*/*/*/package.json'].slice(0, stack_1.MAX_APP_DEPTH - 1), {
347
+ cwd: workspacePath,
348
+ onlyFiles: true,
349
+ ignore: ['**/node_modules/**', '**/.*/**'],
350
+ });
351
+ const depthOf = (p) => p.split('/').length;
352
+ for (const pkg of nested.sort((a, b) => depthOf(a) - depthOf(b) || a.localeCompare(b))) {
353
+ const dir = path.join(workspacePath, path.dirname(pkg));
354
+ if (!candidates.includes(dir))
355
+ candidates.push(dir);
356
+ }
344
357
  for (const dir of candidates) {
345
358
  const subPkg = await (0, file_utils_1.readJsonFile)(path.join(dir, 'package.json'));
346
359
  if (!subPkg)
@@ -68,4 +68,13 @@ exports.JSX_TRANSLATABLE_ATTRS = [
68
68
  'accessibilityHint',
69
69
  'label',
70
70
  'description',
71
+ // Common copy props of custom components (<ScreenHeader subtitle="…" />, <Toast message="…" />).
72
+ 'subtitle',
73
+ 'heading',
74
+ 'caption',
75
+ 'message',
76
+ 'hint',
77
+ 'helperText',
78
+ 'emptyText',
79
+ 'tooltip',
71
80
  ];
@@ -51,6 +51,7 @@ exports.createMessageTCall = createMessageTCall;
51
51
  const generator_1 = __importDefault(require("@babel/generator"));
52
52
  const t = __importStar(require("@babel/types"));
53
53
  const string_utils_1 = require("./string-utils");
54
+ const icu_message_1 = require("./icu-message");
54
55
  /** Phrasing elements that live inside a sentence. Anything else is block-level. */
55
56
  const INLINE_TAGS = new Set([
56
57
  'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'data', 'del', 'dfn', 'em', 'i', 'ins', 'kbd',
@@ -68,7 +69,6 @@ const RESERVED_NAMES = new Set([
68
69
  'context', 'defaultValue', 'fallbackLng', 'interpolation', 'joinArrays', 'keySeparator', 'lng', 'lngs',
69
70
  'ns', 'nsSeparator', 'ordinal', 'postProcess', 'replace', 'returnDetails', 'returnObjects', 'skipInterpolation',
70
71
  ]);
71
- const COUNT_NAME = /^(?:count|total|num|n|length)$|(?:Count|Length)$/;
72
72
  /** Words ending in "s" that are not regular plural nouns. */
73
73
  const NOT_PLURAL_NOUNS = new Set([
74
74
  'is', 'was', 'has', 'does', 'this', 'its', 'his', 'hers', 'ours', 'yours', 'theirs', 'us', 'yes', 'plus',
@@ -587,7 +587,9 @@ function singular(word) {
587
587
  * that doesn't agree with it ("in", "left", "selected", …).
588
588
  */
589
589
  function makePlural(pieces, entries) {
590
- const countLike = entries.filter((e) => e.kind === 'placeholder' && COUNT_NAME.test(e.name));
590
+ // The same rule translations use to add plurals (`count`, `itemCount`, and counted nouns
591
+ // like `likes` or `files`), so the source gets a plural whenever its translations do.
592
+ const countLike = entries.filter((e) => e.kind === 'placeholder' && (0, icu_message_1.isCountLikeName)(e.name));
591
593
  if (countLike.length !== 1)
592
594
  return undefined;
593
595
  // `data?.count` or `n ?? 0` may be undefined at runtime → "NaN items".
@@ -185,7 +185,17 @@ function analyzeModuleConstants(ast) {
185
185
  });
186
186
  return plans;
187
187
  }
188
- function planFor({ name, init, references, reassigned, exported, anchor, insert }) {
188
+ /** `[...] as const`, `{...} satisfies T`, `<T>[...]`, `([...])`: the list itself. */
189
+ function unwrapExpression(p) {
190
+ let cur = p;
191
+ while (cur.isTSAsExpression() || cur.isTSSatisfiesExpression() || cur.isTSTypeAssertion() || cur.isParenthesizedExpression()) {
192
+ cur = cur.get('expression');
193
+ }
194
+ return cur;
195
+ }
196
+ function planFor({ name, init: declared, references, reassigned, exported, anchor, insert }) {
197
+ // A list written `as const` (common for tab and option lists) was skipped without a report.
198
+ const init = unwrapExpression(declared);
189
199
  const isCopy = (s) => (0, string_utils_1.isTranslatableText)(s.trim());
190
200
  // Per "field" ('' for an array of strings): the UI-copy literals that would
191
201
  // become keys, every translatable literal (reported if not provable), and
@@ -11,5 +11,10 @@
11
11
  export declare function isLatinScript(locale: string): boolean;
12
12
  /** Letters left once placeholders, tags and entities are removed. */
13
13
  export declare function hasWords(text: string | undefined): boolean;
14
+ /**
15
+ * Only acronyms ("API", "PDF", "URL", "HTTP/2"): written the same in every
16
+ * script, so Japanese or Hindi keeping them is a translation, not a miss.
17
+ */
18
+ export declare function isAcronymOnly(text: string): boolean;
14
19
  /** `translated` is the untouched source, into a language where that cannot be a translation. */
15
20
  export declare function isUntranslatedInto(source: string, translated: string, targetLocale: string): boolean;
@@ -11,6 +11,7 @@
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.isLatinScript = isLatinScript;
13
13
  exports.hasWords = hasWords;
14
+ exports.isAcronymOnly = isAcronymOnly;
14
15
  exports.isUntranslatedInto = isUntranslatedInto;
15
16
  /** Is the locale written in Latin script (where an unchanged word can be a real translation)? */
16
17
  function isLatinScript(locale) {
@@ -28,7 +29,15 @@ function hasWords(text) {
28
29
  const stripped = text.replace(/%\(\w+\)[-#0 +]*\d*(?:\.\d+)?[a-zA-Z]|%[sdif%]|\{[^{}]*\}|<[^>]*>|&[#\w]+;|\[\s*#\s*VAR_\d+\s*#\s*\]/gi, ' ');
29
30
  return /\p{L}{2,}/u.test(stripped);
30
31
  }
32
+ /**
33
+ * Only acronyms ("API", "PDF", "URL", "HTTP/2"): written the same in every
34
+ * script, so Japanese or Hindi keeping them is a translation, not a miss.
35
+ */
36
+ function isAcronymOnly(text) {
37
+ const words = text.match(/\p{L}[\p{L}\p{N}]*/gu);
38
+ return !!words && words.every((w) => /^\p{Lu}[\p{Lu}\p{N}]+$/u.test(w));
39
+ }
31
40
  /** `translated` is the untouched source, into a language where that cannot be a translation. */
32
41
  function isUntranslatedInto(source, translated, targetLocale) {
33
- return !isLatinScript(targetLocale) && translated.trim() === source.trim() && hasWords(source);
42
+ return !isLatinScript(targetLocale) && translated.trim() === source.trim() && hasWords(source) && !isAcronymOnly(source);
34
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.15",
3
+ "version": "0.3.17",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",