@babelize/engine 0.3.13 → 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.
- package/dist/analysis/analyze.js +1 -1
- package/dist/docs/docs-translate.d.ts +8 -0
- package/dist/docs/docs-translate.js +17 -0
- package/dist/local/formatter.d.ts +9 -0
- package/dist/local/formatter.js +42 -0
- package/dist/local/hosted-provider.d.ts +11 -0
- package/dist/local/hosted-provider.js +34 -6
- package/dist/modules/extractor/extract.d.ts +6 -0
- package/dist/modules/extractor/extract.js +15 -1
- package/dist/orchestrator.js +1 -1
- package/dist/utils/source-language.d.ts +29 -0
- package/dist/utils/source-language.js +115 -0
- package/package.json +1 -1
package/dist/analysis/analyze.js
CHANGED
|
@@ -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 };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ByokProvider } from '@babelize/types';
|
|
2
2
|
import type { FormalitySetting } from '../modules/translator/formality';
|
|
3
3
|
import type { TranslationProvider } from '../providers/types';
|
|
4
|
+
import { type ContentFormatter } from '../local/formatter';
|
|
4
5
|
export interface DocsConfig {
|
|
5
6
|
/** Globs of source pages, relative to the project root (`content/docs/**`). */
|
|
6
7
|
include: string[];
|
|
@@ -42,6 +43,11 @@ export interface DocsTranslateDeps {
|
|
|
42
43
|
};
|
|
43
44
|
/** `detail`: a step inside the current one (a batch), not a new step. */
|
|
44
45
|
onProgress?: (message: string, detail?: boolean) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Formats a translated file before it's compared and written. Default: the
|
|
48
|
+
* project's own prettier/biome (null: leave files as rebuilt).
|
|
49
|
+
*/
|
|
50
|
+
format?: ContentFormatter | null;
|
|
45
51
|
}
|
|
46
52
|
export interface DocsFailure {
|
|
47
53
|
file: string;
|
|
@@ -58,6 +64,8 @@ export interface DocsTranslateReport {
|
|
|
58
64
|
/** Segment translations produced this run (not reused from the lockfile). */
|
|
59
65
|
translated: number;
|
|
60
66
|
reused: number;
|
|
67
|
+
/** Lockfile entries dropped because no page has their text any more. */
|
|
68
|
+
pruned: number;
|
|
61
69
|
failures: DocsFailure[];
|
|
62
70
|
changes: {
|
|
63
71
|
added: string[];
|
|
@@ -62,6 +62,7 @@ const fast_glob_1 = __importDefault(require("fast-glob"));
|
|
|
62
62
|
const translate_1 = require("../modules/translator/translate");
|
|
63
63
|
const translate_core_1 = require("../local/translate-core");
|
|
64
64
|
const check_project_1 = require("../qa/check-project");
|
|
65
|
+
const formatter_1 = require("../local/formatter");
|
|
65
66
|
const locale_files_1 = require("../qa/locale-files");
|
|
66
67
|
const markdown_segments_1 = require("./markdown-segments");
|
|
67
68
|
/** `docs` from .babelize/config.json; null when it isn't configured. */
|
|
@@ -205,11 +206,15 @@ async function translateDocs(opts, deps = {}) {
|
|
|
205
206
|
pages.push(page);
|
|
206
207
|
}
|
|
207
208
|
const lock = await readLock(projectDir);
|
|
209
|
+
// Translated files as the project's formatter writes them, so CI format
|
|
210
|
+
// checks pass and an unchanged page isn't rewritten every run.
|
|
211
|
+
const format = deps.format !== undefined ? deps.format : await (0, formatter_1.createContentFormatter)(projectDir);
|
|
208
212
|
const report = {
|
|
209
213
|
files: pages.length,
|
|
210
214
|
segments: pages.reduce((n, p) => n + p.segments.length, 0),
|
|
211
215
|
translated: 0,
|
|
212
216
|
reused: 0,
|
|
217
|
+
pruned: 0,
|
|
213
218
|
failures: [],
|
|
214
219
|
changes: { added: [], modified: [] },
|
|
215
220
|
outputs: {},
|
|
@@ -311,6 +316,8 @@ async function translateDocs(opts, deps = {}) {
|
|
|
311
316
|
if (translations.size === 0 && page.segments.length > 0)
|
|
312
317
|
continue;
|
|
313
318
|
const target = targetPath(page.rel, locale, docs);
|
|
319
|
+
if (format)
|
|
320
|
+
content = await format(target, content);
|
|
314
321
|
report.outputs[target] = content;
|
|
315
322
|
const existing = await fs_1.promises.readFile(path.join(projectDir, target), 'utf8').catch(() => null);
|
|
316
323
|
if (existing === content)
|
|
@@ -322,6 +329,16 @@ async function translateDocs(opts, deps = {}) {
|
|
|
322
329
|
}
|
|
323
330
|
}
|
|
324
331
|
}
|
|
332
|
+
// Translations of text no page has any more (an edited paragraph's old
|
|
333
|
+
// version) are dropped. Every configured page was read, so this is complete;
|
|
334
|
+
// locales outside this run keep their translations of current text.
|
|
335
|
+
const live = new Set(pages.flatMap((p) => p.segments.map((s) => hashOf(s.message))));
|
|
336
|
+
for (const h of Object.keys(lock.segments)) {
|
|
337
|
+
if (live.has(h))
|
|
338
|
+
continue;
|
|
339
|
+
delete lock.segments[h];
|
|
340
|
+
report.pruned++;
|
|
341
|
+
}
|
|
325
342
|
if (!opts.dryRun) {
|
|
326
343
|
await fs_1.promises.mkdir(path.dirname(path.join(projectDir, exports.DOCS_LOCKFILE)), { recursive: true });
|
|
327
344
|
await fs_1.promises.writeFile(path.join(projectDir, exports.DOCS_LOCKFILE), `${JSON.stringify(lock, null, 2)}\n`);
|
|
@@ -23,4 +23,13 @@ export declare function detectFormatter(projectRoot: string): Promise<(typeof FO
|
|
|
23
23
|
export declare function formatChangedFiles(projectDir: string, workDir: string, changedFiles: string[], opts?: {
|
|
24
24
|
timeoutMs?: number;
|
|
25
25
|
}): Promise<FormatResult | null>;
|
|
26
|
+
/** Formats one file's new content as the project's formatter would; returns it unchanged when it can't. */
|
|
27
|
+
export type ContentFormatter = (relPath: string, content: string) => Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* A formatter for content written straight into the project (translated
|
|
30
|
+
* docs), so it can be compared with what is on disk before writing. Uses the
|
|
31
|
+
* project's own prettier (in process, with its config and .prettierignore) or
|
|
32
|
+
* biome (stdin). Null when the project has neither installed.
|
|
33
|
+
*/
|
|
34
|
+
export declare function createContentFormatter(projectDir: string): Promise<ContentFormatter | null>;
|
|
26
35
|
export {};
|
package/dist/local/formatter.js
CHANGED
|
@@ -35,8 +35,10 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.detectFormatter = detectFormatter;
|
|
37
37
|
exports.formatChangedFiles = formatChangedFiles;
|
|
38
|
+
exports.createContentFormatter = createContentFormatter;
|
|
38
39
|
const node_child_process_1 = require("node:child_process");
|
|
39
40
|
const promises_1 = require("node:fs/promises");
|
|
41
|
+
const node_module_1 = require("node:module");
|
|
40
42
|
const path = __importStar(require("node:path"));
|
|
41
43
|
const node_util_1 = require("node:util");
|
|
42
44
|
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
@@ -103,3 +105,43 @@ async function formatChangedFiles(projectDir, workDir, changedFiles, opts = {})
|
|
|
103
105
|
await (0, promises_1.unlink)(link).catch(() => { });
|
|
104
106
|
}
|
|
105
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* A formatter for content written straight into the project (translated
|
|
110
|
+
* docs), so it can be compared with what is on disk before writing. Uses the
|
|
111
|
+
* project's own prettier (in process, with its config and .prettierignore) or
|
|
112
|
+
* biome (stdin). Null when the project has neither installed.
|
|
113
|
+
*/
|
|
114
|
+
async function createContentFormatter(projectDir) {
|
|
115
|
+
const formatter = await detectFormatter(projectDir);
|
|
116
|
+
if (!formatter)
|
|
117
|
+
return null;
|
|
118
|
+
if (formatter.name === 'prettier') {
|
|
119
|
+
let prettier;
|
|
120
|
+
try {
|
|
121
|
+
prettier = (0, node_module_1.createRequire)(path.join(projectDir, 'package.json'))('prettier');
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
const ignorePath = path.join(projectDir, '.prettierignore');
|
|
127
|
+
return async (relPath, content) => {
|
|
128
|
+
const file = path.join(projectDir, relPath);
|
|
129
|
+
try {
|
|
130
|
+
const info = await prettier.getFileInfo(file, { ignorePath });
|
|
131
|
+
if (info.ignored || !info.inferredParser)
|
|
132
|
+
return content;
|
|
133
|
+
return await prettier.format(content, { ...(await prettier.resolveConfig(file)), filepath: file });
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return content;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const bin = path.join(projectDir, 'node_modules', '.bin', formatter.name);
|
|
141
|
+
if (!(await (0, promises_1.lstat)(bin).catch(() => null)))
|
|
142
|
+
return null;
|
|
143
|
+
return (relPath, content) => new Promise((resolve) => {
|
|
144
|
+
const child = (0, node_child_process_1.execFile)(bin, ['format', `--stdin-file-path=${relPath}`], { cwd: projectDir, timeout: 30000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, NO_COLOR: '1' } }, (err, stdout) => resolve(err || !stdout ? content : stdout));
|
|
145
|
+
child.stdin?.end(content);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
@@ -9,6 +9,17 @@ import type { KeyResult, TranslationBatchRequest, TranslationProvider } from '..
|
|
|
9
9
|
*/
|
|
10
10
|
/** Server limit on entries per request. */
|
|
11
11
|
export declare const HOSTED_MAX_BATCH: 100;
|
|
12
|
+
/**
|
|
13
|
+
* Most source characters per request. The hosted model's time grows with the
|
|
14
|
+
* text it gets, and the server gives a batch 90 s: a batch of long docs
|
|
15
|
+
* paragraphs at the entry limit never finished (#406). About 1,200 characters
|
|
16
|
+
* measured at 30–80 s; longer text goes out in more, parallel requests.
|
|
17
|
+
*/
|
|
18
|
+
export declare const HOSTED_MAX_BATCH_CHARS = 1200;
|
|
19
|
+
/** Requests of at most `maxEntries` entries and `maxChars` characters (a longer entry goes alone). */
|
|
20
|
+
export declare function chunkEntries<T extends {
|
|
21
|
+
value: string;
|
|
22
|
+
}>(entries: T[], maxEntries: number, maxChars: number): T[][];
|
|
12
23
|
/**
|
|
13
24
|
* Per-attempt timeout. Longer than the server's total model budget (90 s),
|
|
14
25
|
* so the server finishes — or gives up uncharged — before we retry.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostedTranslationProvider = exports.HOSTED_MAX_IN_FLIGHT = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH = void 0;
|
|
3
|
+
exports.HostedTranslationProvider = exports.HOSTED_MAX_IN_FLIGHT = exports.HostedTranslationError = exports.BILLING_URL = exports.API_KEYS_URL = exports.HOSTED_CREDITS_HEADER = exports.HOSTED_MODEL_HEADER = exports.HOSTED_REQUEST_TIMEOUT_MS = exports.HOSTED_MAX_BATCH_CHARS = exports.HOSTED_MAX_BATCH = void 0;
|
|
4
|
+
exports.chunkEntries = chunkEntries;
|
|
4
5
|
exports.parseRetryAfterMs = parseRetryAfterMs;
|
|
5
6
|
const node_crypto_1 = require("node:crypto");
|
|
6
7
|
const language_codes_1 = require("../modules/translator/language-codes");
|
|
@@ -15,6 +16,31 @@ const types_1 = require("@babelize/types");
|
|
|
15
16
|
*/
|
|
16
17
|
/** Server limit on entries per request. */
|
|
17
18
|
exports.HOSTED_MAX_BATCH = types_1.TRANSLATE_BATCH_LIMITS.maxEntries;
|
|
19
|
+
/**
|
|
20
|
+
* Most source characters per request. The hosted model's time grows with the
|
|
21
|
+
* text it gets, and the server gives a batch 90 s: a batch of long docs
|
|
22
|
+
* paragraphs at the entry limit never finished (#406). About 1,200 characters
|
|
23
|
+
* measured at 30–80 s; longer text goes out in more, parallel requests.
|
|
24
|
+
*/
|
|
25
|
+
exports.HOSTED_MAX_BATCH_CHARS = 1200;
|
|
26
|
+
/** Requests of at most `maxEntries` entries and `maxChars` characters (a longer entry goes alone). */
|
|
27
|
+
function chunkEntries(entries, maxEntries, maxChars) {
|
|
28
|
+
const chunks = [];
|
|
29
|
+
let current = [];
|
|
30
|
+
let chars = 0;
|
|
31
|
+
for (const e of entries) {
|
|
32
|
+
if (current.length > 0 && (current.length >= maxEntries || chars + e.value.length > maxChars)) {
|
|
33
|
+
chunks.push(current);
|
|
34
|
+
current = [];
|
|
35
|
+
chars = 0;
|
|
36
|
+
}
|
|
37
|
+
current.push(e);
|
|
38
|
+
chars += e.value.length;
|
|
39
|
+
}
|
|
40
|
+
if (current.length > 0)
|
|
41
|
+
chunks.push(current);
|
|
42
|
+
return chunks;
|
|
43
|
+
}
|
|
18
44
|
/**
|
|
19
45
|
* Per-attempt timeout. Longer than the server's total model budget (90 s),
|
|
20
46
|
* so the server finishes — or gives up uncharged — before we retry.
|
|
@@ -119,16 +145,18 @@ class HostedTranslationProvider {
|
|
|
119
145
|
}
|
|
120
146
|
return true;
|
|
121
147
|
});
|
|
148
|
+
// Sent side by side, as many at a time as the in-flight cap allows.
|
|
122
149
|
const remote = new Map();
|
|
123
|
-
|
|
124
|
-
|
|
150
|
+
const chunks = chunkEntries(sendable, exports.HOSTED_MAX_BATCH, exports.HOSTED_MAX_BATCH_CHARS);
|
|
151
|
+
const results = await Promise.all(chunks.map((entries) => {
|
|
125
152
|
const keys = new Set(entries.map((e) => e.key));
|
|
126
153
|
const hints = request.hints
|
|
127
154
|
? Object.fromEntries(Object.entries(request.hints).filter(([k]) => keys.has(k)))
|
|
128
155
|
: undefined;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
156
|
+
return this.withSlot(() => this.post({ ...request, entries, hints }));
|
|
157
|
+
}));
|
|
158
|
+
for (const r of results.flat())
|
|
159
|
+
remote.set(r.key, r);
|
|
132
160
|
return request.entries.flatMap((e) => {
|
|
133
161
|
const r = local.get(e.key) ?? remote.get(e.key);
|
|
134
162
|
return r ? [r] : [];
|
|
@@ -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
|
-
|
|
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);
|
package/dist/orchestrator.js
CHANGED
|
@@ -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