@babelize/engine 0.3.14 → 0.3.15

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.
@@ -145,7 +145,7 @@ async function analyzeWorkspace(workspacePath, options = {}) {
145
145
  const phases = (types_1.FRAMEWORK_CONFIGS[framework] ?? types_1.FRAMEWORK_CONFIGS.unknown).phases;
146
146
  // Same ICU decision as a local translate run (whose translator is an LLM).
147
147
  const icuOptions = await (0, extraction_options_1.resolveIcuOptions)(workspace, true);
148
- const { extraction } = await (0, extract_1.extractStrings)(workspace, undefined, icuOptions);
148
+ const { extraction } = await (0, extract_1.extractStrings)(workspace, undefined, { ...icuOptions, sourceLocale });
149
149
  const existing = workspace.localeFormat === 'json' ? ((await (0, locale_builder_1.readLocaleFile)(workspace, sourceLocale)) ?? {}) : {};
150
150
  const { keyGeneration } = (0, keygen_1.generateKeys)(extraction.strings, existing);
151
151
  let injection = { modifiedFiles: [], skippedFiles: [], totalInjections: 0 };
@@ -8,6 +8,12 @@ export interface ExtractOptions {
8
8
  sentences?: boolean;
9
9
  /** Generate ICU plurals in sentences ("{count} items"). Needs an LLM translator. Default true. */
10
10
  plurals?: boolean;
11
+ /**
12
+ * The project's source locale. Literals written in a script it doesn't use
13
+ * (demo content in another language) and language-code badges are left as
14
+ * written, not extracted (#413).
15
+ */
16
+ sourceLocale?: string;
11
17
  }
12
18
  export declare function extractStrings(workspace: WorkspaceInfo, filesToProcess?: string[], extractOptions?: ExtractOptions): Promise<Phase1Result>;
13
19
  /**
@@ -50,6 +50,7 @@ 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
52
  const source_scope_1 = require("../../utils/source-scope");
53
+ const source_language_1 = require("../../utils/source-language");
53
54
  /** Frameworks whose injection strategies can render a JSX sentence as one message. */
54
55
  const SENTENCE_FRAMEWORKS = new Set(['react', 'nextjs', 'react-native']);
55
56
  async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
@@ -94,7 +95,20 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
94
95
  if (!result)
95
96
  continue;
96
97
  const { relativePath, extracted } = result;
97
- strings.push(...extracted.strings);
98
+ for (const s of extracted.strings) {
99
+ const why = (0, source_language_1.notSourceLanguage)(s.text, extractOptions.sourceLocale);
100
+ if (!why) {
101
+ strings.push(s);
102
+ continue;
103
+ }
104
+ // Left in the code as written: translating it would change what it shows.
105
+ notInjected.push({
106
+ file: s.file,
107
+ key: '',
108
+ text: s.text,
109
+ reason: why === 'language_code' ? 'language code, kept as written' : 'not in the source language, kept as written',
110
+ });
111
+ }
98
112
  warnings.push(...extracted.warnings);
99
113
  if (extracted.notInjected)
100
114
  notInjected.push(...extracted.notInjected);
@@ -157,7 +157,7 @@ async function runEngineV2(config) {
157
157
  if (!icuOptions.sentences && workspace.framework !== 'django') {
158
158
  logger_1.engineLogger.warn('i18next-icu not loaded by the project i18n config; keeping JSX sentences as fragments');
159
159
  }
160
- const { extraction } = await (0, extract_1.extractStrings)(workspace, config.filesToProcess, icuOptions);
160
+ const { extraction } = await (0, extract_1.extractStrings)(workspace, config.filesToProcess, { ...icuOptions, sourceLocale: config.sourceLocale });
161
161
  if (extraction.warnings && extraction.warnings.length > 0) {
162
162
  logger_1.engineLogger.warn('Extraction warnings', { count: extraction.warnings.length, warnings: extraction.warnings });
163
163
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Literals that aren't text of the project in its source language (#413):
3
+ * demo content that shows another language on purpose (an Arabic RTL
4
+ * preview, a "日本語" sample) and language-code badges ("en", "FR"). Extracting
5
+ * and translating them breaks what they show — the Arabic preview became
6
+ * Spanish, "en" became "に関する".
7
+ *
8
+ * Detected by script, not by language: a literal whose letters are almost all
9
+ * in a script the source language isn't written in. Latin is never foreign to
10
+ * a non-Latin source (brand and product names). Text in the source's own
11
+ * script but another language ("Bienvenue" in an English project) needs real
12
+ * language identification and is not detected.
13
+ */
14
+ /** Scripts checked, as Unicode script names (`\p{Script=…}`). */
15
+ declare const SCRIPTS: readonly ["Latin", "Cyrillic", "Greek", "Armenian", "Georgian", "Arabic", "Hebrew", "Syriac", "Thaana", "Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Oriya", "Tamil", "Telugu", "Kannada", "Malayalam", "Sinhala", "Thai", "Lao", "Tibetan", "Myanmar", "Khmer", "Ethiopic", "Hangul", "Hiragana", "Katakana", "Han"];
16
+ type Script = (typeof SCRIPTS)[number];
17
+ /** The scripts the source locale is written in; null when unknown (nothing is flagged). */
18
+ export declare function sourceScripts(sourceLocale: string): Script[] | null;
19
+ /** True when `text` is written in a script `sourceLocale` doesn't use (see the module comment). */
20
+ export declare function isForeignScript(text: string, sourceLocale: string): boolean;
21
+ /**
22
+ * A language or locale code shown as a badge: `en`, `FR`, `pt-BR`, `zh-Hant`, `fil-PH`.
23
+ * Lowercase or uppercase only ("Fr" is not a badge), a code Intl knows, and
24
+ * not an English word ("no", "it", "is", "to"…).
25
+ */
26
+ export declare function isLanguageCode(text: string): boolean;
27
+ /** Why a literal isn't source-language text, or null when it is. */
28
+ export declare function notSourceLanguage(text: string, sourceLocale: string | undefined): 'foreign_script' | 'language_code' | null;
29
+ export {};
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ /**
3
+ * Literals that aren't text of the project in its source language (#413):
4
+ * demo content that shows another language on purpose (an Arabic RTL
5
+ * preview, a "日本語" sample) and language-code badges ("en", "FR"). Extracting
6
+ * and translating them breaks what they show — the Arabic preview became
7
+ * Spanish, "en" became "に関する".
8
+ *
9
+ * Detected by script, not by language: a literal whose letters are almost all
10
+ * in a script the source language isn't written in. Latin is never foreign to
11
+ * a non-Latin source (brand and product names). Text in the source's own
12
+ * script but another language ("Bienvenue" in an English project) needs real
13
+ * language identification and is not detected.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.sourceScripts = sourceScripts;
17
+ exports.isForeignScript = isForeignScript;
18
+ exports.isLanguageCode = isLanguageCode;
19
+ exports.notSourceLanguage = notSourceLanguage;
20
+ /** Scripts checked, as Unicode script names (`\p{Script=…}`). */
21
+ const SCRIPTS = [
22
+ 'Latin', 'Cyrillic', 'Greek', 'Armenian', 'Georgian', 'Arabic', 'Hebrew', 'Syriac', 'Thaana',
23
+ 'Devanagari', 'Bengali', 'Gurmukhi', 'Gujarati', 'Oriya', 'Tamil', 'Telugu', 'Kannada', 'Malayalam',
24
+ 'Sinhala', 'Thai', 'Lao', 'Tibetan', 'Myanmar', 'Khmer', 'Ethiopic', 'Hangul', 'Hiragana', 'Katakana', 'Han',
25
+ ];
26
+ const SCRIPT_RE = Object.fromEntries(SCRIPTS.map((s) => [s, new RegExp(`\\p{Script=${s}}`, 'u')]));
27
+ /** ISO 15924 code (from `Intl.Locale#maximize`) → the scripts text in it uses. */
28
+ const ISO_SCRIPTS = {
29
+ Latn: ['Latin'], Cyrl: ['Cyrillic'], Grek: ['Greek'], Armn: ['Armenian'], Geor: ['Georgian'],
30
+ Arab: ['Arabic'], Hebr: ['Hebrew'], Syrc: ['Syriac'], Thaa: ['Thaana'], Deva: ['Devanagari'],
31
+ Beng: ['Bengali'], Guru: ['Gurmukhi'], Gujr: ['Gujarati'], Orya: ['Oriya'], Taml: ['Tamil'],
32
+ Telu: ['Telugu'], Knda: ['Kannada'], Mlym: ['Malayalam'], Sinh: ['Sinhala'], Thai: ['Thai'],
33
+ Laoo: ['Lao'], Tibt: ['Tibetan'], Mymr: ['Myanmar'], Khmr: ['Khmer'], Ethi: ['Ethiopic'],
34
+ Kore: ['Hangul', 'Han'], Jpan: ['Hiragana', 'Katakana', 'Han'], Hans: ['Han'], Hant: ['Han'],
35
+ };
36
+ /** The scripts the source locale is written in; null when unknown (nothing is flagged). */
37
+ function sourceScripts(sourceLocale) {
38
+ try {
39
+ const script = new Intl.Locale(sourceLocale).maximize().script;
40
+ return (script && ISO_SCRIPTS[script]) || null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ function scriptOf(letter) {
47
+ for (const s of SCRIPTS)
48
+ if (SCRIPT_RE[s].test(letter))
49
+ return s;
50
+ return null;
51
+ }
52
+ /** At least this share of a literal's letters in foreign scripts makes it foreign. */
53
+ const FOREIGN_SHARE = 0.8;
54
+ /** True when `text` is written in a script `sourceLocale` doesn't use (see the module comment). */
55
+ function isForeignScript(text, sourceLocale) {
56
+ const own = sourceScripts(sourceLocale);
57
+ if (!own)
58
+ return false;
59
+ const letters = [...text].filter((c) => /\p{L}/u.test(c));
60
+ if (letters.length < 2)
61
+ return false;
62
+ let foreign = 0;
63
+ for (const c of letters) {
64
+ const s = scriptOf(c);
65
+ // Latin in a non-Latin source is brand/product names, not another language.
66
+ if (s && !own.includes(s) && s !== 'Latin')
67
+ foreign++;
68
+ }
69
+ return foreign / letters.length >= FOREIGN_SHARE;
70
+ }
71
+ /** Two-letter language codes that are also English words, kept as text. */
72
+ const CODE_WORDS = new Set(['am', 'an', 'as', 'be', 'he', 'hi', 'id', 'is', 'it', 'me', 'my', 'no', 'or', 'so', 'to', 'us', 'we']);
73
+ let displayNames;
74
+ /**
75
+ * A language or locale code shown as a badge: `en`, `FR`, `pt-BR`, `zh-Hant`, `fil-PH`.
76
+ * Lowercase or uppercase only ("Fr" is not a badge), a code Intl knows, and
77
+ * not an English word ("no", "it", "is", "to"…).
78
+ */
79
+ function isLanguageCode(text) {
80
+ const t = text.trim();
81
+ const m = /^([a-z]{2,3}|[A-Z]{2,3})(?:[-_]([A-Za-z]{2,4}|\d{3}))?$/.exec(t);
82
+ if (!m)
83
+ return false;
84
+ const base = m[1].toLowerCase();
85
+ // Bare codes are two letters: three-letter ones are words ("cat", "art", "new")
86
+ // or acronyms (API, SDK) far more often than badges.
87
+ if (!m[2] && m[1].length === 3)
88
+ return false;
89
+ if (!m[2] && CODE_WORDS.has(base))
90
+ return false;
91
+ if (displayNames === undefined) {
92
+ try {
93
+ displayNames = new Intl.DisplayNames(['en'], { type: 'language', fallback: 'none' });
94
+ }
95
+ catch {
96
+ displayNames = null;
97
+ }
98
+ }
99
+ if (!displayNames)
100
+ return false;
101
+ try {
102
+ return !!displayNames.of(base);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ /** Why a literal isn't source-language text, or null when it is. */
109
+ function notSourceLanguage(text, sourceLocale) {
110
+ if (isLanguageCode(text))
111
+ return 'language_code';
112
+ if (sourceLocale && isForeignScript(text, sourceLocale))
113
+ return 'foreign_script';
114
+ return null;
115
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",