@babelize/engine 0.3.3 → 0.3.5
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/config.d.ts +8 -8
- package/dist/detection/i18n.d.ts +2 -0
- package/dist/detection/i18n.js +8 -3
- package/dist/local/translate-core.js +8 -3
- package/dist/modules/extractor/extract.d.ts +6 -0
- package/dist/modules/extractor/extract.js +22 -0
- package/dist/modules/finalization/nextjs-finalize.js +2 -1
- package/dist/modules/injection/inject.js +21 -6
- package/dist/modules/locale-builder/adopted.d.ts +37 -0
- package/dist/modules/locale-builder/adopted.js +181 -0
- package/dist/modules/locale-builder/locales.js +8 -5
- package/dist/modules/translator/translate.js +2 -2
- package/dist/modules/workspace/existing-setup.d.ts +28 -0
- package/dist/modules/workspace/existing-setup.js +126 -0
- package/dist/modules/workspace/validate.js +20 -1
- package/dist/orchestrator.js +89 -21
- package/dist/runtime/types.d.ts +21 -2
- package/dist/utils/ast-helpers.js +28 -0
- package/dist/utils/file-utils.d.ts +16 -2
- package/dist/utils/file-utils.js +11 -4
- package/package.json +1 -1
package/dist/config.d.ts
CHANGED
|
@@ -15,23 +15,23 @@ declare const configSchema: z.ZodObject<{
|
|
|
15
15
|
term: z.ZodString;
|
|
16
16
|
translations: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
17
17
|
}, "strip", z.ZodTypeAny, {
|
|
18
|
-
term: string;
|
|
19
18
|
translations: Record<string, string>;
|
|
20
|
-
}, {
|
|
21
19
|
term: string;
|
|
20
|
+
}, {
|
|
22
21
|
translations: Record<string, string>;
|
|
22
|
+
term: string;
|
|
23
23
|
}>, "many">>;
|
|
24
24
|
}, "strip", z.ZodTypeAny, {
|
|
25
25
|
neverTranslate: string[];
|
|
26
26
|
alwaysTranslateAs: {
|
|
27
|
-
term: string;
|
|
28
27
|
translations: Record<string, string>;
|
|
28
|
+
term: string;
|
|
29
29
|
}[];
|
|
30
30
|
}, {
|
|
31
31
|
neverTranslate?: string[] | undefined;
|
|
32
32
|
alwaysTranslateAs?: {
|
|
33
|
-
term: string;
|
|
34
33
|
translations: Record<string, string>;
|
|
34
|
+
term: string;
|
|
35
35
|
}[] | undefined;
|
|
36
36
|
}>>;
|
|
37
37
|
lockfilePath: z.ZodOptional<z.ZodString>;
|
|
@@ -40,23 +40,23 @@ declare const configSchema: z.ZodObject<{
|
|
|
40
40
|
sourceLocale: string;
|
|
41
41
|
targetLocales: string[];
|
|
42
42
|
dryRun: boolean;
|
|
43
|
-
framework?: "react" | "nextjs" | "vue" | "static" | "
|
|
43
|
+
framework?: "react" | "nextjs" | "vue" | "static" | "django" | "react-native" | "unknown" | undefined;
|
|
44
44
|
projectId?: string | undefined;
|
|
45
45
|
sourceDir?: string | undefined;
|
|
46
46
|
localesDir?: string | undefined;
|
|
47
47
|
glossary?: {
|
|
48
48
|
neverTranslate: string[];
|
|
49
49
|
alwaysTranslateAs: {
|
|
50
|
-
term: string;
|
|
51
50
|
translations: Record<string, string>;
|
|
51
|
+
term: string;
|
|
52
52
|
}[];
|
|
53
53
|
} | undefined;
|
|
54
54
|
lockfilePath?: string | undefined;
|
|
55
55
|
}, {
|
|
56
56
|
workspacePath: string;
|
|
57
|
+
framework?: "react" | "nextjs" | "vue" | "static" | "django" | "react-native" | "unknown" | undefined;
|
|
57
58
|
sourceLocale?: string | undefined;
|
|
58
59
|
targetLocales?: string[] | undefined;
|
|
59
|
-
framework?: "react" | "nextjs" | "vue" | "static" | "unknown" | "django" | "react-native" | undefined;
|
|
60
60
|
dryRun?: boolean | undefined;
|
|
61
61
|
projectId?: string | undefined;
|
|
62
62
|
sourceDir?: string | undefined;
|
|
@@ -64,8 +64,8 @@ declare const configSchema: z.ZodObject<{
|
|
|
64
64
|
glossary?: {
|
|
65
65
|
neverTranslate?: string[] | undefined;
|
|
66
66
|
alwaysTranslateAs?: {
|
|
67
|
-
term: string;
|
|
68
67
|
translations: Record<string, string>;
|
|
68
|
+
term: string;
|
|
69
69
|
}[] | undefined;
|
|
70
70
|
} | undefined;
|
|
71
71
|
lockfilePath?: string | undefined;
|
package/dist/detection/i18n.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { RepoFiles } from './stack';
|
|
2
2
|
export type I18nLibraryId = 'next-intl' | 'next-i18next' | 'react-i18next' | 'i18next' | 'vue-i18n' | 'react-intl' | 'lingui' | 'django';
|
|
3
3
|
export declare const I18N_LIBRARY_NAMES: Record<I18nLibraryId, string>;
|
|
4
|
+
/** The i18n library a set of package.json dependency names points at (most specific first). */
|
|
5
|
+
export declare function libraryFromDependencies(deps: Iterable<string>): I18nLibraryId | null;
|
|
4
6
|
export type SourceLanguageBasis = 'config' | 'files' | 'default';
|
|
5
7
|
export interface DetectedI18n {
|
|
6
8
|
library: {
|
package/dist/detection/i18n.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.I18N_LIBRARY_NAMES = void 0;
|
|
4
|
+
exports.libraryFromDependencies = libraryFromDependencies;
|
|
4
5
|
exports.detectI18n = detectI18n;
|
|
5
6
|
/**
|
|
6
7
|
* What a repository already has for i18n, read from a file listing and a few
|
|
@@ -30,6 +31,11 @@ const LIBRARY_DEPS = [
|
|
|
30
31
|
['lingui', ['@lingui/core', '@lingui/react']],
|
|
31
32
|
['i18next', ['i18next']],
|
|
32
33
|
];
|
|
34
|
+
/** The i18n library a set of package.json dependency names points at (most specific first). */
|
|
35
|
+
function libraryFromDependencies(deps) {
|
|
36
|
+
const names = new Set(deps);
|
|
37
|
+
return LIBRARY_DEPS.find(([, pkgs]) => pkgs.some((n) => names.has(n)))?.[0] ?? null;
|
|
38
|
+
}
|
|
33
39
|
const IGNORED = /(?:^|\/)(?:node_modules|\.git|vendor|dist|build|\.next|out|coverage|__tests__|__fixtures__|fixtures|tests?|e2e)\//;
|
|
34
40
|
/** Files that commonly declare the default locale, checked in this order. */
|
|
35
41
|
const CONFIG_FILE = /(?:^|\/)(?:i18n(?:\/(?:routing|request|config|index))?|i18n\.config|next\.config|next-i18next\.config|nuxt\.config|src\/i18n(?:\/index)?|src\/plugins\/i18n|lingui\.config)\.(?:[cm]?[jt]s|json)$/;
|
|
@@ -80,10 +86,9 @@ async function detectI18n(files, framework) {
|
|
|
80
86
|
library = { id: 'django', name: exports.I18N_LIBRARY_NAMES.django };
|
|
81
87
|
}
|
|
82
88
|
else {
|
|
83
|
-
const
|
|
84
|
-
const found = LIBRARY_DEPS.find(([, names]) => names.some((n) => deps.has(n)));
|
|
89
|
+
const found = libraryFromDependencies(await readDeps(files, paths));
|
|
85
90
|
if (found)
|
|
86
|
-
library = { id: found
|
|
91
|
+
library = { id: found, name: exports.I18N_LIBRARY_NAMES[found] };
|
|
87
92
|
}
|
|
88
93
|
// Existing locale files: the set with the most locales wins.
|
|
89
94
|
let locales = [];
|
|
@@ -299,6 +299,7 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
299
299
|
let framework;
|
|
300
300
|
let publicDir = 'public';
|
|
301
301
|
let localeFormat = 'json';
|
|
302
|
+
let adoptedSetup = false;
|
|
302
303
|
try {
|
|
303
304
|
const { workspace } = await (0, workspace_1.validateWorkspace)({
|
|
304
305
|
workspacePath: temp.dir,
|
|
@@ -311,6 +312,7 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
311
312
|
framework = workspace.framework;
|
|
312
313
|
publicDir = workspace.publicDir;
|
|
313
314
|
localeFormat = workspace.localeFormat;
|
|
315
|
+
adoptedSetup = !!workspace.existingSetup;
|
|
314
316
|
}
|
|
315
317
|
catch (err) {
|
|
316
318
|
throw new LocalTranslateError(err.message, 'unsupported_framework');
|
|
@@ -324,7 +326,9 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
324
326
|
// `--to ja` after `--to fr,de` would silently drop fr and de. Unless the
|
|
325
327
|
// user asked to replace the set, earlier locales stay in it; their
|
|
326
328
|
// translations come from the lockfile, so only new strings cost tokens.
|
|
327
|
-
|
|
329
|
+
// The project's own i18n setup (adopted) keeps every language it has
|
|
330
|
+
// untouched: only the requested ones are translated.
|
|
331
|
+
const earlier = adoptedSetup ? [] : await existingTargetLocales(temp.dir, publicDir, localeFormat, opts.sourceLocale);
|
|
328
332
|
const keptLocales = opts.replace ? [] : earlier.filter((l) => !opts.targetLocales.includes(l));
|
|
329
333
|
const droppedLocales = opts.replace ? earlier.filter((l) => !opts.targetLocales.includes(l)) : [];
|
|
330
334
|
const targetLocales = [...opts.targetLocales, ...keptLocales];
|
|
@@ -386,7 +390,7 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
386
390
|
if (locale.locale === opts.sourceLocale || locale.noFile)
|
|
387
391
|
continue;
|
|
388
392
|
const rel = locale.path.split(path.sep).join('/');
|
|
389
|
-
if (locale.content !== undefined) {
|
|
393
|
+
if (locale.content !== undefined && !rel.endsWith('.json')) {
|
|
390
394
|
// A merged catalogue (Django .po): written exactly as the engine
|
|
391
395
|
// produced it. The merge never drops existing translations.
|
|
392
396
|
for (const f of [{ path: rel, content: locale.content, encoding: 'utf8' }, ...(locale.extraFiles ?? [])]) {
|
|
@@ -412,7 +416,8 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
412
416
|
if (path.relative(temp.dir, abs).startsWith('..'))
|
|
413
417
|
continue;
|
|
414
418
|
await (0, promises_1.mkdir)(path.dirname(abs), { recursive: true });
|
|
415
|
-
|
|
419
|
+
// Exact content: the project's own locale file, in its key order and indentation.
|
|
420
|
+
await (0, promises_1.writeFile)(abs, locale.content ?? `${JSON.stringify(sortKeysDeep(locale.data), null, 2)}\n`);
|
|
416
421
|
}
|
|
417
422
|
// The QA report (.babelize/local/report.json) stays out of git; the
|
|
418
423
|
// lockfile next to it is committed. Shipped with the run's other changes.
|
|
@@ -10,6 +10,12 @@ export interface ExtractOptions {
|
|
|
10
10
|
plurals?: boolean;
|
|
11
11
|
}
|
|
12
12
|
export declare function extractStrings(workspace: WorkspaceInfo, filesToProcess?: string[], extractOptions?: ExtractOptions): Promise<Phase1Result>;
|
|
13
|
+
/**
|
|
14
|
+
* Next.js files that never render UI: App Router route handlers
|
|
15
|
+
* (`app/<segments>/route.ts`), Pages Router API routes (`pages/api/<file>`) and
|
|
16
|
+
* middleware / proxy at the app root.
|
|
17
|
+
*/
|
|
18
|
+
export declare function isNextServerOnlyFile(filePath: string): boolean;
|
|
13
19
|
export declare function extractStringsFromFile(content: string, filePath: string, detectFormats?: boolean, options?: {
|
|
14
20
|
relaxComponentGuard?: boolean;
|
|
15
21
|
framework?: string;
|
|
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.extractStrings = extractStrings;
|
|
37
|
+
exports.isNextServerOnlyFile = isNextServerOnlyFile;
|
|
37
38
|
exports.extractStringsFromFile = extractStringsFromFile;
|
|
38
39
|
const path = __importStar(require("path"));
|
|
39
40
|
const types_1 = require("../../runtime/types");
|
|
@@ -116,12 +117,33 @@ function isBabelizeGenerated(content) {
|
|
|
116
117
|
const head = content.slice(0, 500);
|
|
117
118
|
return GENERATED_FILE_MARKERS.some((marker) => head.includes(marker));
|
|
118
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Next.js files that never render UI: App Router route handlers
|
|
122
|
+
* (`app/<segments>/route.ts`), Pages Router API routes (`pages/api/<file>`) and
|
|
123
|
+
* middleware / proxy at the app root.
|
|
124
|
+
*/
|
|
125
|
+
function isNextServerOnlyFile(filePath) {
|
|
126
|
+
const segments = filePath.split(/[\\/]/).filter(Boolean);
|
|
127
|
+
const base = segments[segments.length - 1] ?? '';
|
|
128
|
+
const dirs = segments.slice(0, -1);
|
|
129
|
+
if (/^route\.[cm]?[jt]sx?$/.test(base) && dirs.includes('app'))
|
|
130
|
+
return true;
|
|
131
|
+
const pages = dirs.indexOf('pages');
|
|
132
|
+
if (pages !== -1 && dirs[pages + 1] === 'api')
|
|
133
|
+
return true;
|
|
134
|
+
// middleware.ts / proxy.ts (Next 16) sit next to app/, never inside a route or component folder.
|
|
135
|
+
return /^(?:middleware|proxy)\.[cm]?[jt]s$/.test(base) && !dirs.some((d) => d === 'app' || d === 'pages' || d === 'components');
|
|
136
|
+
}
|
|
119
137
|
async function extractStringsFromFile(content, filePath, detectFormats, options) {
|
|
120
138
|
// Files Babelize generated itself (i18n config, next-intl request config)
|
|
121
139
|
// hold config values such as bindI18n: 'languageChanged loaded'. A re-run
|
|
122
140
|
// used to extract those and inject t() into the i18n config, breaking it.
|
|
123
141
|
if (isBabelizeGenerated(content))
|
|
124
142
|
return { strings: [], warnings: [] };
|
|
143
|
+
// Next.js server-only code (route handlers, API routes, middleware) answers
|
|
144
|
+
// requests, not people: its strings are API messages and header values.
|
|
145
|
+
if (options?.framework === 'nextjs' && isNextServerOnlyFile(filePath))
|
|
146
|
+
return { strings: [], warnings: [] };
|
|
125
147
|
// Django: gettext calls, translate tags and hardcoded text in templates/forms/models/views.
|
|
126
148
|
if (options?.framework === 'django') {
|
|
127
149
|
return (0, extract_1.extractDjangoFile)(content, filePath, { icu: options.plurals === true });
|
|
@@ -271,7 +271,8 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
271
271
|
`Make sure it loads messages from ${toPosix(workspace.publicDir)}/locales/<locale>.json.`);
|
|
272
272
|
}
|
|
273
273
|
else {
|
|
274
|
-
|
|
274
|
+
// publicDir is relative to the workspace (apps/web/public in a monorepo), not the app.
|
|
275
|
+
const sampleLocale = (0, file_utils_1.localeFilePath)(workspace.path, workspace.publicDir, 'json', '__LOCALE__').file;
|
|
275
276
|
let messagesImportPath = toPosix(path.relative(requestDir, sampleLocale));
|
|
276
277
|
if (!messagesImportPath.startsWith('.'))
|
|
277
278
|
messagesImportPath = `./${messagesImportPath}`;
|
|
@@ -238,6 +238,20 @@ function renderMessage(strategy, key, message, options) {
|
|
|
238
238
|
return null;
|
|
239
239
|
return { node: ast_helpers_1.t.jsxExpressionContainer((0, jsx_message_1.createMessageTCall)(key, message)) };
|
|
240
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* A translated string literal keeps the whitespace around its text, which
|
|
243
|
+
* the message itself leaves out: a mail body `Page: ${href}` followed by two
|
|
244
|
+
* line breaks becomes a template literal holding t(…) and the line breaks,
|
|
245
|
+
* not a bare t() call that drops them.
|
|
246
|
+
*/
|
|
247
|
+
function keepEdgeWhitespace(original, call) {
|
|
248
|
+
const leading = original.match(/^\s*/)?.[0] ?? '';
|
|
249
|
+
const trailing = original.length > leading.length ? (original.match(/\s*$/)?.[0] ?? '') : '';
|
|
250
|
+
if (!leading && !trailing)
|
|
251
|
+
return call;
|
|
252
|
+
const quasi = (cooked, tail) => ast_helpers_1.t.templateElement({ cooked, raw: cooked.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') }, tail);
|
|
253
|
+
return ast_helpers_1.t.templateLiteral([quasi(leading, false), quasi(trailing, true)], [call]);
|
|
254
|
+
}
|
|
241
255
|
/**
|
|
242
256
|
* Replace a JSXText node with `{t(...)}` without changing the rendered
|
|
243
257
|
* spacing. In JSX, whitespace at the edge of a text node is significant when
|
|
@@ -616,8 +630,9 @@ positions, options = {}) {
|
|
|
616
630
|
return null;
|
|
617
631
|
const names = [];
|
|
618
632
|
const exprs = [];
|
|
619
|
-
const
|
|
620
|
-
|
|
633
|
+
const full = (0, ast_helpers_1.extractExpressionContent)(path.node, names, exprs);
|
|
634
|
+
const text = full?.trim();
|
|
635
|
+
if (!full || !text)
|
|
621
636
|
return null;
|
|
622
637
|
const extractionId = `${filePath}:${path.node.loc?.start.line || 0}:${(0, string_utils_1.hashString)(text)}`;
|
|
623
638
|
const key = keyMapping.get(extractionId);
|
|
@@ -633,7 +648,7 @@ positions, options = {}) {
|
|
|
633
648
|
byName.set(names[i], exprs[i]);
|
|
634
649
|
}
|
|
635
650
|
if (byName.size === 0)
|
|
636
|
-
return { key, values: null };
|
|
651
|
+
return { key, values: null, full };
|
|
637
652
|
const props = [...byName].map(([name, expr]) => {
|
|
638
653
|
const shorthand = ast_helpers_1.t.isIdentifier(expr) && expr.name === name;
|
|
639
654
|
const keyNode = ast_helpers_1.t.isValidIdentifier(name) ? ast_helpers_1.t.identifier(name) : ast_helpers_1.t.stringLiteral(name);
|
|
@@ -641,7 +656,7 @@ positions, options = {}) {
|
|
|
641
656
|
// fallback string inside (`name || 'your business'`) couldn't be wired.
|
|
642
657
|
return ast_helpers_1.t.objectProperty(keyNode, expr, false, shorthand);
|
|
643
658
|
});
|
|
644
|
-
return { key, values: ast_helpers_1.t.objectExpression(props) };
|
|
659
|
+
return { key, values: ast_helpers_1.t.objectExpression(props), full };
|
|
645
660
|
};
|
|
646
661
|
// Pre-scan to determine if we should fall back to vanilla strategy and identify hooks needed
|
|
647
662
|
(0, ast_helpers_1.traverse)(ast, {
|
|
@@ -959,7 +974,7 @@ positions, options = {}) {
|
|
|
959
974
|
const args = [ast_helpers_1.t.stringLiteral(message.key)];
|
|
960
975
|
if (message.values)
|
|
961
976
|
args.push(message.values);
|
|
962
|
-
const call = ast_helpers_1.t.callExpression(ast_helpers_1.t.identifier(name), args);
|
|
977
|
+
const call = keepEdgeWhitespace(message.full, ast_helpers_1.t.callExpression(ast_helpers_1.t.identifier(name), args));
|
|
963
978
|
const line = path.node.loc?.start.line || 0;
|
|
964
979
|
const column = path.node.loc?.start.column || 0;
|
|
965
980
|
const original = (0, ast_helpers_1.generate)(path.node).code;
|
|
@@ -1021,7 +1036,7 @@ positions, options = {}) {
|
|
|
1021
1036
|
if (!source)
|
|
1022
1037
|
return;
|
|
1023
1038
|
const tFunctionName = pickTranslator(path, source);
|
|
1024
|
-
path.replaceWith(useTranslatorName((0, ast_helpers_1.createTCall)(key), tFunctionName));
|
|
1039
|
+
path.replaceWith(keepEdgeWhitespace(path.node.value, useTranslatorName((0, ast_helpers_1.createTCall)(key), tFunctionName)));
|
|
1025
1040
|
injections.push({
|
|
1026
1041
|
file: filePath,
|
|
1027
1042
|
line,
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ExtractedString, LocaleData, LocaleFile, NotInjectedString, WorkspaceInfo } from '../../runtime/types';
|
|
2
|
+
import type { LockfileData } from '../lockfile/schema';
|
|
3
|
+
export interface AdoptedLocale {
|
|
4
|
+
data: LocaleData;
|
|
5
|
+
raw: string;
|
|
6
|
+
}
|
|
7
|
+
/** The locale files as they are before the run (the translator writes to the same paths). */
|
|
8
|
+
export declare function readAdoptedLocales(workspace: WorkspaceInfo, locales: string[]): Promise<Record<string, AdoptedLocale | null>>;
|
|
9
|
+
/**
|
|
10
|
+
* Record the translations already in the project's locale files in the
|
|
11
|
+
* lockfile, so they are reused instead of re-translated. A file value wins
|
|
12
|
+
* over the lockfile's (someone edited the file); a key whose source text
|
|
13
|
+
* changed since the lockfile recorded it is left for re-translation.
|
|
14
|
+
*/
|
|
15
|
+
export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): LockfileData;
|
|
16
|
+
/** Keys of `source` missing (or empty) in each target file: the work for a run without a lockfile. */
|
|
17
|
+
export declare function missingKeysByLocale(flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): Record<string, string[]>;
|
|
18
|
+
/**
|
|
19
|
+
* A target locale file for an adopted setup: its existing content (order,
|
|
20
|
+
* extra keys, non-string values) with `values` filled in, or — for a new
|
|
21
|
+
* file — the source file's structure and order. Serialized like the source
|
|
22
|
+
* file (indentation, trailing newline) and handed to hosts as exact content.
|
|
23
|
+
*/
|
|
24
|
+
export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null): LocaleFile;
|
|
25
|
+
/**
|
|
26
|
+
* What the user needs to know after translating an adopted setup: where the
|
|
27
|
+
* translations went, strings in the code that aren't wired up, and where a
|
|
28
|
+
* new language still has to be registered.
|
|
29
|
+
*/
|
|
30
|
+
export declare function adoptedSetupNotes(workspace: WorkspaceInfo, sourceLocale: string, targetLocales: string[], hardcoded: NotInjectedString[]): string[];
|
|
31
|
+
/**
|
|
32
|
+
* Strings found in code that an adopted setup leaves alone (reported, never
|
|
33
|
+
* injected): UI text only. Template/JSX text and attributes, and literals in
|
|
34
|
+
* component files; literals in plain .js/.ts (servers, scripts, utilities)
|
|
35
|
+
* are mostly API messages and identifiers, and would drown the real ones.
|
|
36
|
+
*/
|
|
37
|
+
export declare function hardcodedStrings(strings: ExtractedString[], workspace: WorkspaceInfo): NotInjectedString[];
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readAdoptedLocales = readAdoptedLocales;
|
|
4
|
+
exports.seedLockfileFromLocaleFiles = seedLockfileFromLocaleFiles;
|
|
5
|
+
exports.missingKeysByLocale = missingKeysByLocale;
|
|
6
|
+
exports.adoptedLocaleFile = adoptedLocaleFile;
|
|
7
|
+
exports.adoptedSetupNotes = adoptedSetupNotes;
|
|
8
|
+
exports.hardcodedStrings = hardcodedStrings;
|
|
9
|
+
/**
|
|
10
|
+
* Locale files of an adopted i18n setup (#367): the app's own `<locale>.json`
|
|
11
|
+
* files in its own locale directory. Their translations are the project's —
|
|
12
|
+
* kept, never re-translated while their source text is unchanged — and a run
|
|
13
|
+
* writes them back in the file's own key order and indentation, with nothing
|
|
14
|
+
* Babelize-specific (`_meta`) added.
|
|
15
|
+
*/
|
|
16
|
+
const fs_1 = require("fs");
|
|
17
|
+
const i18n_1 = require("../../detection/i18n");
|
|
18
|
+
const file_utils_1 = require("../../utils/file-utils");
|
|
19
|
+
const keygen_1 = require("../keygen");
|
|
20
|
+
const hasher_1 = require("../lockfile/hasher");
|
|
21
|
+
const language_codes_1 = require("../translator/language-codes");
|
|
22
|
+
/** The locale files as they are before the run (the translator writes to the same paths). */
|
|
23
|
+
async function readAdoptedLocales(workspace, locales) {
|
|
24
|
+
const out = {};
|
|
25
|
+
for (const locale of locales) {
|
|
26
|
+
const raw = await fs_1.promises.readFile((0, file_utils_1.workspaceLocaleFile)(workspace, locale).file, 'utf8').catch(() => null);
|
|
27
|
+
let data = null;
|
|
28
|
+
if (raw !== null) {
|
|
29
|
+
try {
|
|
30
|
+
const parsed = JSON.parse(raw);
|
|
31
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
|
|
32
|
+
data = parsed;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new Error(`${(0, file_utils_1.workspaceLocaleFile)(workspace, locale).relativeFile} is not valid JSON. Fix it and run again. Nothing was changed.`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
out[locale] = data && raw !== null ? { data, raw } : null;
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Record the translations already in the project's locale files in the
|
|
44
|
+
* lockfile, so they are reused instead of re-translated. A file value wins
|
|
45
|
+
* over the lockfile's (someone edited the file); a key whose source text
|
|
46
|
+
* changed since the lockfile recorded it is left for re-translation.
|
|
47
|
+
*/
|
|
48
|
+
function seedLockfileFromLocaleFiles(lockfile, flatKeys, targets) {
|
|
49
|
+
const next = JSON.parse(JSON.stringify(lockfile));
|
|
50
|
+
const now = new Date().toISOString();
|
|
51
|
+
for (const [locale, file] of Object.entries(targets)) {
|
|
52
|
+
if (!file)
|
|
53
|
+
continue;
|
|
54
|
+
for (const [key, value] of Object.entries((0, keygen_1.flattenLocaleData)(file.data))) {
|
|
55
|
+
const source = flatKeys[key];
|
|
56
|
+
if (source === undefined || !value)
|
|
57
|
+
continue;
|
|
58
|
+
const hash = (0, hasher_1.hashSourceString)(source);
|
|
59
|
+
const entry = next.keys[key] ?? { sourceHash: hash, translatedAt: now, languages: {}, metadata: {} };
|
|
60
|
+
if (entry.sourceHash !== hash)
|
|
61
|
+
continue;
|
|
62
|
+
if (entry.languages[locale] !== value) {
|
|
63
|
+
// Not what Babelize wrote: the project's own, kept through glossary edits too.
|
|
64
|
+
entry.metadata = { ...(entry.metadata ?? {}), [locale]: { external: true } };
|
|
65
|
+
}
|
|
66
|
+
entry.languages[locale] = value;
|
|
67
|
+
next.keys[key] = entry;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return next;
|
|
71
|
+
}
|
|
72
|
+
/** Keys of `source` missing (or empty) in each target file: the work for a run without a lockfile. */
|
|
73
|
+
function missingKeysByLocale(flatKeys, targets) {
|
|
74
|
+
const out = {};
|
|
75
|
+
for (const [locale, file] of Object.entries(targets)) {
|
|
76
|
+
const have = file ? (0, keygen_1.flattenLocaleData)(file.data) : {};
|
|
77
|
+
out[locale] = Object.keys(flatKeys).filter((k) => !have[k]);
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A target locale file for an adopted setup: its existing content (order,
|
|
83
|
+
* extra keys, non-string values) with `values` filled in, or — for a new
|
|
84
|
+
* file — the source file's structure and order. Serialized like the source
|
|
85
|
+
* file (indentation, trailing newline) and handed to hosts as exact content.
|
|
86
|
+
*/
|
|
87
|
+
function adoptedLocaleFile(workspace, locale, source, values, existing) {
|
|
88
|
+
const data = (fill(existing ? clone(existing.data) : {}, source.data, values, '', !existing) ?? {});
|
|
89
|
+
const style = existing ?? source;
|
|
90
|
+
const { relativeFile } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
|
|
91
|
+
// Nothing new for an existing file: its bytes stay exactly as they are.
|
|
92
|
+
const unchanged = existing && JSON.stringify(data) === JSON.stringify(existing.data);
|
|
93
|
+
return {
|
|
94
|
+
locale,
|
|
95
|
+
path: relativeFile,
|
|
96
|
+
data,
|
|
97
|
+
isNew: !existing,
|
|
98
|
+
isRTL: (0, language_codes_1.isRTL)(locale),
|
|
99
|
+
content: unchanged ? existing.raw : `${JSON.stringify(data, null, indentOf(style.raw))}${style.raw.endsWith('\n') ? '\n' : ''}`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Walk the source structure, writing translated leaves into `target` (new
|
|
104
|
+
* keys land in source order). Undefined: nothing to write at this path.
|
|
105
|
+
*/
|
|
106
|
+
function fill(target, source, values, prefix, carryPrimitives) {
|
|
107
|
+
if (typeof source === 'string')
|
|
108
|
+
return values[prefix] || target;
|
|
109
|
+
if (Array.isArray(source)) {
|
|
110
|
+
const out = Array.isArray(target) ? target : [];
|
|
111
|
+
source.forEach((child, i) => {
|
|
112
|
+
const filled = fill(out[i], child, values, key(prefix, String(i)), carryPrimitives);
|
|
113
|
+
if (filled !== undefined)
|
|
114
|
+
out[i] = filled;
|
|
115
|
+
});
|
|
116
|
+
return out.length > 0 || target !== undefined ? out : undefined;
|
|
117
|
+
}
|
|
118
|
+
if (source && typeof source === 'object') {
|
|
119
|
+
const out = (target && typeof target === 'object' && !Array.isArray(target) ? target : {});
|
|
120
|
+
for (const [k, child] of Object.entries(source)) {
|
|
121
|
+
if (!prefix && k === '_meta')
|
|
122
|
+
continue;
|
|
123
|
+
const filled = fill(out[k], child, values, key(prefix, k), carryPrimitives);
|
|
124
|
+
if (filled !== undefined)
|
|
125
|
+
out[k] = filled;
|
|
126
|
+
}
|
|
127
|
+
return Object.keys(out).length > 0 || target !== undefined ? out : undefined;
|
|
128
|
+
}
|
|
129
|
+
// Numbers, booleans, null: not translated; a new file gets the source's.
|
|
130
|
+
return target === undefined && carryPrimitives ? source : target;
|
|
131
|
+
}
|
|
132
|
+
function key(prefix, k) {
|
|
133
|
+
return prefix ? `${prefix}.${k}` : k;
|
|
134
|
+
}
|
|
135
|
+
function clone(v) {
|
|
136
|
+
return JSON.parse(JSON.stringify(v));
|
|
137
|
+
}
|
|
138
|
+
/** The file's indentation (2 spaces when it can't be told). */
|
|
139
|
+
function indentOf(raw) {
|
|
140
|
+
const m = /\n([ \t]+)["{[]/.exec(raw);
|
|
141
|
+
return m ? m[1] : 2;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* What the user needs to know after translating an adopted setup: where the
|
|
145
|
+
* translations went, strings in the code that aren't wired up, and where a
|
|
146
|
+
* new language still has to be registered.
|
|
147
|
+
*/
|
|
148
|
+
function adoptedSetupNotes(workspace, sourceLocale, targetLocales, hardcoded) {
|
|
149
|
+
const setup = workspace.existingSetup;
|
|
150
|
+
if (!setup)
|
|
151
|
+
return [];
|
|
152
|
+
const library = i18n_1.I18N_LIBRARY_NAMES[setup.library];
|
|
153
|
+
const notes = [`Used the project's existing ${library} setup: translations are in ${setup.localeDir}/. No code or i18n config was changed.`];
|
|
154
|
+
if (hardcoded.length > 0) {
|
|
155
|
+
const files = new Set(hardcoded.map((h) => h.file)).size;
|
|
156
|
+
notes.push(`${hardcoded.length} hardcoded string(s) in ${files} file(s) look translatable but aren't in ${setup.localeDir}/${sourceLocale}.json. ` +
|
|
157
|
+
`They were left as they are: add them to your ${library} setup to translate them.`);
|
|
158
|
+
}
|
|
159
|
+
const added = targetLocales.filter((l) => !workspace.existingLocales.includes(l));
|
|
160
|
+
if (added.length > 0 && setup.languageLists.length > 0) {
|
|
161
|
+
notes.push(`New language(s) ${added.join(', ')}: add them where the app lists its languages (${setup.languageLists.join(', ')}), or the app won't offer them.`);
|
|
162
|
+
}
|
|
163
|
+
return notes;
|
|
164
|
+
}
|
|
165
|
+
const COMPONENT_FILE = /\.(?:vue|jsx|tsx|html?)$/;
|
|
166
|
+
/**
|
|
167
|
+
* Strings found in code that an adopted setup leaves alone (reported, never
|
|
168
|
+
* injected): UI text only. Template/JSX text and attributes, and literals in
|
|
169
|
+
* component files; literals in plain .js/.ts (servers, scripts, utilities)
|
|
170
|
+
* are mostly API messages and identifiers, and would drown the real ones.
|
|
171
|
+
*/
|
|
172
|
+
function hardcodedStrings(strings, workspace) {
|
|
173
|
+
const library = workspace.existingSetup ? i18n_1.I18N_LIBRARY_NAMES[workspace.existingSetup.library] : 'i18n';
|
|
174
|
+
const ui = strings.filter((s) => s.context === 'jsx-text' || s.context === 'jsx-attr' || COMPONENT_FILE.test(s.file));
|
|
175
|
+
return ui.map((s) => ({
|
|
176
|
+
file: s.file,
|
|
177
|
+
key: '',
|
|
178
|
+
text: s.text,
|
|
179
|
+
reason: `hardcoded text; the project's own ${library} setup is used as it is, so code is not changed`,
|
|
180
|
+
}));
|
|
181
|
+
}
|
|
@@ -18,11 +18,13 @@ async function handleBaseLocale(workspace, generatedKeys, sourceLocale = 'en', d
|
|
|
18
18
|
assertSafeLocale(sourceLocale);
|
|
19
19
|
if (workspace.localeFormat === 'po')
|
|
20
20
|
return gettextSourceLocale(generatedKeys, sourceLocale);
|
|
21
|
-
const localePaths = (0, file_utils_1.
|
|
21
|
+
const localePaths = (0, file_utils_1.workspaceLocaleFile)(workspace, sourceLocale);
|
|
22
22
|
const localesDir = localePaths.dir;
|
|
23
23
|
const localeFilePathTarget = localePaths.file;
|
|
24
24
|
const relativeLocaleFilePath = localePaths.relativeFile;
|
|
25
|
-
|
|
25
|
+
// An adopted setup's source file is the app's own: read, never rewritten.
|
|
26
|
+
const adopted = !!workspace.existingSetup;
|
|
27
|
+
if (!dryRun && !adopted)
|
|
26
28
|
await (0, file_utils_1.ensureDir)(localesDir);
|
|
27
29
|
const exists = await (0, file_utils_1.pathExists)(localeFilePathTarget);
|
|
28
30
|
let existingData = {};
|
|
@@ -56,7 +58,7 @@ async function handleBaseLocale(workspace, generatedKeys, sourceLocale = 'en', d
|
|
|
56
58
|
language: sourceLocale,
|
|
57
59
|
},
|
|
58
60
|
};
|
|
59
|
-
if (!dryRun)
|
|
61
|
+
if (!dryRun && !adopted)
|
|
60
62
|
await (0, file_utils_1.writeJsonFile)(localeFilePathTarget, dataWithMeta, true);
|
|
61
63
|
const sourceLocaleFile = {
|
|
62
64
|
locale: sourceLocale,
|
|
@@ -64,6 +66,7 @@ async function handleBaseLocale(workspace, generatedKeys, sourceLocale = 'en', d
|
|
|
64
66
|
data: dataWithMeta,
|
|
65
67
|
isNew: !exists,
|
|
66
68
|
isRTL: (0, language_codes_1.isRTL)(sourceLocale),
|
|
69
|
+
...(adopted ? { noFile: true } : {}),
|
|
67
70
|
};
|
|
68
71
|
return {
|
|
69
72
|
localeHandling: {
|
|
@@ -112,7 +115,7 @@ async function readLocaleFile(workspace, locale) {
|
|
|
112
115
|
if (workspace.localeFormat !== 'json') {
|
|
113
116
|
throw new Error(`Locale format '${workspace.localeFormat}' reading not yet implemented`);
|
|
114
117
|
}
|
|
115
|
-
const { file } = (0, file_utils_1.
|
|
118
|
+
const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
|
|
116
119
|
return (0, file_utils_1.readJsonFile)(file);
|
|
117
120
|
}
|
|
118
121
|
async function checkExistingTargetLocales(workspace, targetLocales) {
|
|
@@ -120,7 +123,7 @@ async function checkExistingTargetLocales(workspace, targetLocales) {
|
|
|
120
123
|
const missing = [];
|
|
121
124
|
for (const locale of targetLocales) {
|
|
122
125
|
assertSafeLocale(locale);
|
|
123
|
-
const { file } = (0, file_utils_1.
|
|
126
|
+
const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
|
|
124
127
|
if (await (0, file_utils_1.pathExists)(file))
|
|
125
128
|
existing.push(locale);
|
|
126
129
|
else
|
|
@@ -221,7 +221,7 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
|
|
|
221
221
|
// Ensure locale output directories exist for all target locales
|
|
222
222
|
if (!dryRun) {
|
|
223
223
|
for (const locale of targetLocales) {
|
|
224
|
-
const { dir } = (0, file_utils_1.
|
|
224
|
+
const { dir } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale);
|
|
225
225
|
await (0, file_utils_1.ensureDir)(dir);
|
|
226
226
|
}
|
|
227
227
|
}
|
|
@@ -268,7 +268,7 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
|
|
|
268
268
|
};
|
|
269
269
|
const { results: localeResults, errors: localeErrors } = await (0, concurrent_map_1.concurrentMap)(localeTasks, withBudget(async (targetLocale, claimBudget) => {
|
|
270
270
|
const targetLangCode = (0, language_codes_1.toFlores)(targetLocale);
|
|
271
|
-
const localePaths = (0, file_utils_1.
|
|
271
|
+
const localePaths = (0, file_utils_1.workspaceLocaleFile)(workspace, targetLocale);
|
|
272
272
|
const targetPath = localePaths.file;
|
|
273
273
|
const relativePath = localePaths.relativeFile;
|
|
274
274
|
let entriesToTranslate = flatSource;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ExistingI18nSetup } from '../../runtime/types';
|
|
2
|
+
/**
|
|
3
|
+
* An app that already ships its own i18n setup — vue-i18n with
|
|
4
|
+
* frontend/locales/, next-intl with messages/, react-i18next with
|
|
5
|
+
* src/i18n/locales/ — is translated in place: its locale directory and
|
|
6
|
+
* source file are the source of truth, and no second setup is generated
|
|
7
|
+
* next to it (#367).
|
|
8
|
+
*
|
|
9
|
+
* Returns null when there is nothing to adopt: no i18n library, no locale
|
|
10
|
+
* files, or the files are where Babelize writes them (`defaultLocaleDir`,
|
|
11
|
+
* i.e. a setup Babelize generated). Throws, with what to do, when the app
|
|
12
|
+
* has a setup whose files can't be used as they are.
|
|
13
|
+
*/
|
|
14
|
+
export declare function detectExistingSetup(opts: {
|
|
15
|
+
workspacePath: string;
|
|
16
|
+
/** The app's folder (monorepo package), relative to the workspace. */
|
|
17
|
+
appDir: string;
|
|
18
|
+
packageJson: {
|
|
19
|
+
dependencies?: Record<string, string>;
|
|
20
|
+
devDependencies?: Record<string, string>;
|
|
21
|
+
} | null;
|
|
22
|
+
sourceLocale: string;
|
|
23
|
+
/** Where Babelize itself writes `<locale>.json`, relative to the workspace. */
|
|
24
|
+
defaultLocaleDir: string;
|
|
25
|
+
}): Promise<{
|
|
26
|
+
setup: ExistingI18nSetup;
|
|
27
|
+
locales: string[];
|
|
28
|
+
} | null>;
|
|
@@ -0,0 +1,126 @@
|
|
|
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
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.detectExistingSetup = detectExistingSetup;
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
const fast_glob_1 = __importDefault(require("fast-glob"));
|
|
42
|
+
const i18n_1 = require("../../detection/i18n");
|
|
43
|
+
const locale_files_1 = require("../../qa/locale-files");
|
|
44
|
+
const file_utils_1 = require("../../utils/file-utils");
|
|
45
|
+
/**
|
|
46
|
+
* An app that already ships its own i18n setup — vue-i18n with
|
|
47
|
+
* frontend/locales/, next-intl with messages/, react-i18next with
|
|
48
|
+
* src/i18n/locales/ — is translated in place: its locale directory and
|
|
49
|
+
* source file are the source of truth, and no second setup is generated
|
|
50
|
+
* next to it (#367).
|
|
51
|
+
*
|
|
52
|
+
* Returns null when there is nothing to adopt: no i18n library, no locale
|
|
53
|
+
* files, or the files are where Babelize writes them (`defaultLocaleDir`,
|
|
54
|
+
* i.e. a setup Babelize generated). Throws, with what to do, when the app
|
|
55
|
+
* has a setup whose files can't be used as they are.
|
|
56
|
+
*/
|
|
57
|
+
async function detectExistingSetup(opts) {
|
|
58
|
+
const deps = Object.keys({ ...opts.packageJson?.dependencies, ...opts.packageJson?.devDependencies });
|
|
59
|
+
const library = (0, i18n_1.libraryFromDependencies)(deps);
|
|
60
|
+
// Lingui catalogs aren't key → text JSON (.po, or message objects).
|
|
61
|
+
if (!library || library === 'lingui')
|
|
62
|
+
return null;
|
|
63
|
+
if (await (0, file_utils_1.pathExists)(path.join(opts.workspacePath, opts.defaultLocaleDir, `${opts.sourceLocale}.json`)))
|
|
64
|
+
return null;
|
|
65
|
+
const appRoot = path.join(opts.workspacePath, opts.appDir);
|
|
66
|
+
const sets = await (0, locale_files_1.findLocaleFileSets)(appRoot);
|
|
67
|
+
if (sets.length === 0)
|
|
68
|
+
return null;
|
|
69
|
+
const libraryName = i18n_1.I18N_LIBRARY_NAMES[library];
|
|
70
|
+
const rel = (set) => toPosix(path.join(opts.appDir, set.dir));
|
|
71
|
+
const withSource = sets.filter((s) => s.files[opts.sourceLocale]);
|
|
72
|
+
const flat = withSource.filter((s) => s.layout === 'flat');
|
|
73
|
+
if (flat.length === 0) {
|
|
74
|
+
const nested = withSource.find((s) => s.layout === 'namespaced');
|
|
75
|
+
if (nested) {
|
|
76
|
+
throw new Error(`This project already uses ${libraryName} with namespaced locale files (${rel(nested)}/<locale>/<namespace>.json). ` +
|
|
77
|
+
`Babelize translates flat locale files (<locale>.json) only, and won't set up a second i18n configuration next to yours. Nothing was changed.`);
|
|
78
|
+
}
|
|
79
|
+
const biggest = sets.reduce((a, b) => (Object.keys(b.files).length > Object.keys(a.files).length ? b : a));
|
|
80
|
+
const found = Object.keys(biggest.files).sort();
|
|
81
|
+
throw new Error(`This project already uses ${libraryName} with locale files in ${rel(biggest)} (${found.join(', ')}), but none for the source language "${opts.sourceLocale}". ` +
|
|
82
|
+
`Set the source language to the one your ${rel(biggest)} files are written in. Nothing was changed.`);
|
|
83
|
+
}
|
|
84
|
+
// Several candidates: the one with the most languages, then the shallowest.
|
|
85
|
+
const best = flat.sort((a, b) => Object.keys(b.files).length - Object.keys(a.files).length || a.dir.split('/').length - b.dir.split('/').length)[0];
|
|
86
|
+
const locales = Object.keys(best.files).sort();
|
|
87
|
+
const localeDir = rel(best);
|
|
88
|
+
return {
|
|
89
|
+
setup: { library, localeDir, languageLists: await findLanguageLists(appRoot, opts.appDir, locales, opts.sourceLocale) },
|
|
90
|
+
locales,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const CODE_FILES = '**/*.{js,jsx,ts,tsx,mjs,cjs,vue}';
|
|
94
|
+
const MAX_SCANNED_FILES = 3000;
|
|
95
|
+
const MAX_FILE_BYTES = 200000;
|
|
96
|
+
/**
|
|
97
|
+
* Code files that name every language the app ships as a string literal
|
|
98
|
+
* (`{ code: 'fr' }`, `locales: ['en', 'fr']`): where the app registers its
|
|
99
|
+
* languages, so a newly added one may need a line there too. Advisory only.
|
|
100
|
+
*/
|
|
101
|
+
async function findLanguageLists(appRoot, appDir, locales, sourceLocale) {
|
|
102
|
+
const others = locales.filter((l) => l !== sourceLocale);
|
|
103
|
+
if (others.length < 2)
|
|
104
|
+
return [];
|
|
105
|
+
const files = await (0, fast_glob_1.default)(CODE_FILES, {
|
|
106
|
+
cwd: appRoot,
|
|
107
|
+
ignore: locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS.map((d) => `**/${d}/**`),
|
|
108
|
+
onlyFiles: true,
|
|
109
|
+
deep: 8,
|
|
110
|
+
followSymbolicLinks: false,
|
|
111
|
+
});
|
|
112
|
+
const literal = (code) => new RegExp(`['"\`]${code.replace(/[-_]/g, '[-_]')}['"\`]`);
|
|
113
|
+
const patterns = locales.map(literal);
|
|
114
|
+
const found = [];
|
|
115
|
+
for (const file of files.sort().slice(0, MAX_SCANNED_FILES)) {
|
|
116
|
+
const content = await (0, file_utils_1.readFile)(path.join(appRoot, file)).catch(() => '');
|
|
117
|
+
if (!content || content.length > MAX_FILE_BYTES)
|
|
118
|
+
continue;
|
|
119
|
+
if (patterns.every((re) => re.test(content)))
|
|
120
|
+
found.push(toPosix(path.join(appDir, file)));
|
|
121
|
+
}
|
|
122
|
+
return found;
|
|
123
|
+
}
|
|
124
|
+
function toPosix(p) {
|
|
125
|
+
return p.split(path.sep).join('/');
|
|
126
|
+
}
|
|
@@ -48,6 +48,7 @@ const file_utils_1 = require("../../utils/file-utils");
|
|
|
48
48
|
const stack_1 = require("../../detection/stack");
|
|
49
49
|
const django_finalize_1 = require("../finalization/django-finalize");
|
|
50
50
|
const locale_names_1 = require("../../django/locale-names");
|
|
51
|
+
const existing_setup_1 = require("./existing-setup");
|
|
51
52
|
const PY_IGNORE = ['**/node_modules/**', '**/.venv/**', '**/venv/**', '**/site-packages/**', '**/.git/**'];
|
|
52
53
|
/**
|
|
53
54
|
* The Django project root (directory of the shallowest manage.py), relative
|
|
@@ -197,10 +198,27 @@ async function validateWorkspace(config) {
|
|
|
197
198
|
// Expo Router treats as routes.
|
|
198
199
|
publicDir = (await (0, file_utils_1.isDirectory)(path.join(workspacePath, appDir, 'src'))) ? path.join(appDir, 'src') : appDir;
|
|
199
200
|
}
|
|
201
|
+
// The app's own i18n setup, when it has one: translated in place (#367).
|
|
202
|
+
const adopted = localeFormat === 'json' && framework !== 'static'
|
|
203
|
+
? await (0, existing_setup_1.detectExistingSetup)({
|
|
204
|
+
workspacePath,
|
|
205
|
+
appDir,
|
|
206
|
+
packageJson: packageJson ?? null,
|
|
207
|
+
sourceLocale: config.sourceLocale,
|
|
208
|
+
defaultLocaleDir: path.join(publicDir, 'locales'),
|
|
209
|
+
})
|
|
210
|
+
: null;
|
|
211
|
+
if (adopted) {
|
|
212
|
+
logger_1.engineLogger.info('Adopting the project\'s existing i18n setup', { library: adopted.setup.library, localeDir: adopted.setup.localeDir });
|
|
213
|
+
}
|
|
200
214
|
const existingLocales = [];
|
|
201
215
|
let hasLocalesDir = false;
|
|
202
216
|
let localeDirRel = '';
|
|
203
|
-
if (
|
|
217
|
+
if (adopted) {
|
|
218
|
+
hasLocalesDir = true;
|
|
219
|
+
existingLocales.push(...adopted.locales);
|
|
220
|
+
}
|
|
221
|
+
else if (localeFormat === 'po') {
|
|
204
222
|
// Django: <LOCALE_PATHS[0]>/<lang>/LC_MESSAGES/django.po (default <BASE_DIR>/locale)
|
|
205
223
|
localeDirRel = await (0, django_finalize_1.resolveDjangoLocaleDir)(workspacePath, djangoRoot ?? '.');
|
|
206
224
|
const djangoLocaleDir = path.join(workspacePath, localeDirRel);
|
|
@@ -247,6 +265,7 @@ async function validateWorkspace(config) {
|
|
|
247
265
|
packageJson: (packageJson ?? {}),
|
|
248
266
|
formatConfig: config.formatConfig,
|
|
249
267
|
...(framework === 'django' ? { djangoRoot: djangoRoot ?? '.' } : {}),
|
|
268
|
+
...(adopted ? { existingSetup: adopted.setup } : {}),
|
|
250
269
|
};
|
|
251
270
|
return { workspace };
|
|
252
271
|
}
|
package/dist/orchestrator.js
CHANGED
|
@@ -43,6 +43,7 @@ const workspace_2 = require("./utils/workspace");
|
|
|
43
43
|
const extract_1 = require("./modules/extractor/extract");
|
|
44
44
|
const keygen_1 = require("./modules/keygen");
|
|
45
45
|
const locale_builder_1 = require("./modules/locale-builder");
|
|
46
|
+
const adopted_1 = require("./modules/locale-builder/adopted");
|
|
46
47
|
const translate_1 = require("./modules/translator/translate");
|
|
47
48
|
const glossary_1 = require("./modules/glossary");
|
|
48
49
|
const translator_caller_1 = require("./utils/translator-caller");
|
|
@@ -128,10 +129,18 @@ async function runEngineV2(config) {
|
|
|
128
129
|
const { workspace } = await (0, workspace_1.validateWorkspace)(config);
|
|
129
130
|
const frameworkConfig = types_1.FRAMEWORK_CONFIGS[workspace.framework] || types_1.FRAMEWORK_CONFIGS['unknown'];
|
|
130
131
|
config.targetLocales = config.targetLocales.filter((l) => l !== config.sourceLocale);
|
|
132
|
+
// The app's own i18n setup (#367): its locale files, as they are before
|
|
133
|
+
// the run, are the source of truth. Other languages' files are the
|
|
134
|
+
// project's and are never removed.
|
|
135
|
+
const adopted = workspace.existingSetup
|
|
136
|
+
? await (0, adopted_1.readAdoptedLocales)(workspace, [config.sourceLocale, ...config.targetLocales])
|
|
137
|
+
: null;
|
|
131
138
|
// Remove stale locale files from previous runs that are no longer in targetLocales.
|
|
132
139
|
// git reset --hard only resets tracked files; generated locale files are untracked
|
|
133
140
|
// and persist across runs, causing stale languages to appear in outputs.
|
|
134
|
-
|
|
141
|
+
if (!adopted) {
|
|
142
|
+
await (0, workspace_2.removeStaleLocales)(config.workspacePath, config.targetLocales, config.sourceLocale, workspace.localeFormat, workspace.publicDir);
|
|
143
|
+
}
|
|
135
144
|
config.onProgress?.('Extracting strings from codebase...', 'extraction', 'running');
|
|
136
145
|
// One resolved ICU decision for extraction, translation and injection (#248).
|
|
137
146
|
const icuOptions = await (0, extraction_options_1.resolveIcuOptions)(workspace, llmTranslator(config));
|
|
@@ -152,17 +161,24 @@ async function runEngineV2(config) {
|
|
|
152
161
|
// Gate on format-inject phase being in the framework's phases AND formatConfig being enabled (D5).
|
|
153
162
|
// This means static HTML gets format strings as translatable (month names, currency as text)
|
|
154
163
|
// instead of silently dropping them.
|
|
155
|
-
const formatPartitionEnabled = frameworkConfig.phases.includes('format-inject') && config.formatConfig?.enabled;
|
|
156
|
-
const [translatableStrings, formatStrings] =
|
|
157
|
-
?
|
|
158
|
-
:
|
|
164
|
+
const formatPartitionEnabled = !adopted && frameworkConfig.phases.includes('format-inject') && config.formatConfig?.enabled;
|
|
165
|
+
const [translatableStrings, formatStrings] = adopted
|
|
166
|
+
? [[], []]
|
|
167
|
+
: formatPartitionEnabled
|
|
168
|
+
? (0, format_injection_1.partitionFormatStrings)(extraction.strings)
|
|
169
|
+
: [extraction.strings, []];
|
|
170
|
+
// An adopted setup's keys are its source file's. Strings still hardcoded
|
|
171
|
+
// in the code are reported, never turned into new keys or injected.
|
|
172
|
+
if (adopted) {
|
|
173
|
+
extraction.notInjected = [...(extraction.notInjected ?? []), ...(0, adopted_1.hardcodedStrings)(extraction.strings, workspace)];
|
|
174
|
+
}
|
|
159
175
|
const existingLocale = await (0, locale_builder_1.readLocaleFile)(workspace, config.sourceLocale);
|
|
160
176
|
const existingData = existingLocale || {};
|
|
161
177
|
// Strings injected by earlier runs are no longer extracted, but their keys
|
|
162
178
|
// are still in the source locale file. With a lockfile those keys must
|
|
163
179
|
// still be carried into every target locale (and translated for newly
|
|
164
180
|
// added locales), so "nothing new to extract" is not "nothing to do".
|
|
165
|
-
const hasExistingKeys = !!config.projectId && Object.keys(sourceLocaleKeys(existingData)).length > 0;
|
|
181
|
+
const hasExistingKeys = (!!config.projectId || !!adopted) && Object.keys(sourceLocaleKeys(existingData)).length > 0;
|
|
166
182
|
if (translatableStrings.length === 0 && formatStrings.length === 0 && !hasExistingKeys) {
|
|
167
183
|
logger_1.engineLogger.info('No strings found, finishing early');
|
|
168
184
|
return createEmptyResult(startTime, extraction.warnings, extraction.skippedFiles, extraction.notInjected);
|
|
@@ -219,6 +235,9 @@ async function runEngineV2(config) {
|
|
|
219
235
|
// Translations already in the project's .po files win over the lockfile.
|
|
220
236
|
if (gettext)
|
|
221
237
|
lockfile = gettext.seedLockfile(lockfile, flatKeys);
|
|
238
|
+
// Likewise the translations in an adopted setup's locale files.
|
|
239
|
+
if (adopted)
|
|
240
|
+
lockfile = (0, adopted_1.seedLockfileFromLocaleFiles)(lockfile, flatKeys, targetFiles(adopted, config.targetLocales));
|
|
222
241
|
// Pseudo-localization (--provider pseudo) is not a translation: a real
|
|
223
242
|
// run treats pseudo values in the lockfile as missing and translates them.
|
|
224
243
|
// The glossary is loaded once, here: keys whose glossary rules changed
|
|
@@ -333,7 +352,7 @@ async function runEngineV2(config) {
|
|
|
333
352
|
for (const [k, v] of Object.entries(realTranslations)) {
|
|
334
353
|
setNestedKey(cachedData, k, v);
|
|
335
354
|
}
|
|
336
|
-
const localePath = (0, file_utils_1.
|
|
355
|
+
const localePath = (0, file_utils_1.workspaceLocaleFile)(workspace, targetLocale);
|
|
337
356
|
translation.locales.push({
|
|
338
357
|
locale: targetLocale,
|
|
339
358
|
path: localePath.relativeFile,
|
|
@@ -367,15 +386,13 @@ async function runEngineV2(config) {
|
|
|
367
386
|
replaced: overrideReport.replaced.length,
|
|
368
387
|
});
|
|
369
388
|
}
|
|
389
|
+
if (adopted)
|
|
390
|
+
translation.locales = adoptLocales(workspace, adopted, translation.locales, localeHandling.sourceLocale.locale);
|
|
370
391
|
// The translator wrote only this run's strings to disk; write the merged
|
|
371
392
|
// locale (lockfile + new) so the workspace — which the download ZIP is
|
|
372
393
|
// built from — has every translation, including fully cached locales.
|
|
373
|
-
if (!config.dryRun && workspace.localeFormat !== 'po')
|
|
374
|
-
|
|
375
|
-
const { file } = (0, file_utils_1.localeFilePath)(workspace.path, workspace.publicDir, workspace.localeFormat, locale.locale);
|
|
376
|
-
await (0, file_utils_1.writeJsonFile)(file, locale.data, true);
|
|
377
|
-
}
|
|
378
|
-
}
|
|
394
|
+
if (!config.dryRun && workspace.localeFormat !== 'po')
|
|
395
|
+
await writeLocales(workspace, translation.locales);
|
|
379
396
|
// ── Lockfile: update after translation ─────────────────
|
|
380
397
|
config.onProgress?.('Updating lockfile...', 'lockfile', 'running');
|
|
381
398
|
const allTranslatedPerLocale = {};
|
|
@@ -473,7 +490,9 @@ async function runEngineV2(config) {
|
|
|
473
490
|
config.onProgress?.(msg, 'translation', 'warning');
|
|
474
491
|
}
|
|
475
492
|
const translationResult = translatorHealthy
|
|
476
|
-
? await (0, translate_1.translateLocales)(workspace, localeHandling.sourceLocale, config.targetLocales, config.forceTranslation, config.dryRun, config.projectId, (msg) => config.onProgress?.(msg, 'translation', 'running'),
|
|
493
|
+
? await (0, translate_1.translateLocales)(workspace, localeHandling.sourceLocale, config.targetLocales, config.forceTranslation, config.dryRun, config.projectId, (msg) => config.onProgress?.(msg, 'translation', 'running'),
|
|
494
|
+
// Without a lockfile, an adopted setup's existing translations are kept: only missing keys are translated.
|
|
495
|
+
adopted ? (0, adopted_1.missingKeysByLocale)(sourceLocaleKeys(localeHandling.sourceLocale.data), targetFiles(adopted, config.targetLocales)) : undefined, config.providers?.cache, config.byok, contextMap, extractionContextMap, config.providers, { targetPlurals: icuOptions.targetPlurals, pluralValuePlaceholders: gettext?.pluralValuePlaceholders(), progress: translationProgress, maxTranslations: config.maxTranslations })
|
|
477
496
|
: {
|
|
478
497
|
translation: {
|
|
479
498
|
locales: [],
|
|
@@ -495,6 +514,11 @@ async function runEngineV2(config) {
|
|
|
495
514
|
logger_1.engineLogger.error('Translation failed', { errors: errorMsg });
|
|
496
515
|
throw new Error(`Translation failed: ${errorMsg}`);
|
|
497
516
|
}
|
|
517
|
+
if (adopted) {
|
|
518
|
+
translation.locales = adoptLocales(workspace, adopted, translation.locales, localeHandling.sourceLocale.locale, config.targetLocales);
|
|
519
|
+
if (!config.dryRun)
|
|
520
|
+
await writeLocales(workspace, translation.locales);
|
|
521
|
+
}
|
|
498
522
|
const allTranslatedPerLocale = {};
|
|
499
523
|
for (const locale of translation.locales) {
|
|
500
524
|
allTranslatedPerLocale[locale.locale] = (0, keygen_1.flattenLocaleData)(locale.data);
|
|
@@ -565,6 +589,44 @@ function freshTranslations(translation, metadata) {
|
|
|
565
589
|
}
|
|
566
590
|
return n;
|
|
567
591
|
}
|
|
592
|
+
/** The target locales' files of an adopted setup (null: no file yet). */
|
|
593
|
+
function targetFiles(adopted, targetLocales) {
|
|
594
|
+
return Object.fromEntries(targetLocales.map((l) => [l, adopted[l] ?? null]));
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* An adopted setup's target files: this run's values written into each file
|
|
598
|
+
* as it was (its order, extra keys and indentation), or shaped like the
|
|
599
|
+
* source file for a new language. `alsoKeep` adds untouched locales whose
|
|
600
|
+
* file already has everything (no translator call without a lockfile).
|
|
601
|
+
*/
|
|
602
|
+
function adoptLocales(workspace, adopted, locales, sourceLocale, alsoKeep = []) {
|
|
603
|
+
const source = adopted[sourceLocale];
|
|
604
|
+
if (!source)
|
|
605
|
+
return locales;
|
|
606
|
+
const out = locales.map((l) => {
|
|
607
|
+
const existing = adopted[l.locale] ?? null;
|
|
608
|
+
// Without a lockfile the translator returns only the missing keys: the file supplies the rest.
|
|
609
|
+
const values = { ...(existing ? (0, keygen_1.flattenLocaleData)(existing.data) : {}), ...(0, keygen_1.flattenLocaleData)(l.data) };
|
|
610
|
+
return (0, adopted_1.adoptedLocaleFile)(workspace, l.locale, source, values, existing);
|
|
611
|
+
});
|
|
612
|
+
for (const locale of alsoKeep) {
|
|
613
|
+
const existing = adopted[locale];
|
|
614
|
+
if (existing && !out.some((l) => l.locale === locale)) {
|
|
615
|
+
out.push((0, adopted_1.adoptedLocaleFile)(workspace, locale, source, (0, keygen_1.flattenLocaleData)(existing.data), existing));
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
/** Write each locale file: exact `content` when the engine produced it, else sorted JSON. */
|
|
621
|
+
async function writeLocales(workspace, locales) {
|
|
622
|
+
for (const locale of locales) {
|
|
623
|
+
const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale.locale);
|
|
624
|
+
if (locale.content !== undefined)
|
|
625
|
+
await fs.outputFile(file, locale.content);
|
|
626
|
+
else
|
|
627
|
+
await (0, file_utils_1.writeJsonFile)(file, locale.data, true);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
568
630
|
/** Flat key → source text for a source locale file, without the `_meta` block. */
|
|
569
631
|
function sourceLocaleKeys(data) {
|
|
570
632
|
const flat = {};
|
|
@@ -669,8 +731,10 @@ async function finalizePipeline(params) {
|
|
|
669
731
|
const { extraction, keyGeneration, localeHandling, translation, config, startTime, workspace, allTranslatedPerLocale, lockfileStats, tmHits, translationMetadata, formatStrings, frameworkConfig, translatedThisRun, skippedForBudget, keyUsage, gettext, overrideReport, } = params;
|
|
670
732
|
const keyMapping = (0, keygen_1.createKeyMapping)(keyGeneration.keys);
|
|
671
733
|
// Injection: AST-based i18n hook injection (skipped for frameworks like Django)
|
|
734
|
+
// An adopted i18n setup is used as it is: no code, config or dependency changes.
|
|
735
|
+
const adoptedSetup = !!workspace.existingSetup;
|
|
672
736
|
let injection;
|
|
673
|
-
if (frameworkConfig.phases.includes('inject')) {
|
|
737
|
+
if (!adoptedSetup && frameworkConfig.phases.includes('inject')) {
|
|
674
738
|
config.onProgress?.('Injecting translations into code...', 'injection', 'running');
|
|
675
739
|
// Inject exactly the nodes extraction selected (by source offset).
|
|
676
740
|
const positions = new Map();
|
|
@@ -682,14 +746,16 @@ async function finalizePipeline(params) {
|
|
|
682
746
|
else {
|
|
683
747
|
injection = { modifiedFiles: [], skippedFiles: [], totalInjections: 0 };
|
|
684
748
|
}
|
|
685
|
-
const notInjected =
|
|
686
|
-
?
|
|
687
|
-
:
|
|
749
|
+
const notInjected = adoptedSetup
|
|
750
|
+
? (extraction.notInjected ?? [])
|
|
751
|
+
: frameworkConfig.phases.includes('inject')
|
|
752
|
+
? [...(0, not_injected_1.findNotInjected)(keyGeneration, injection), ...(extraction.notInjected ?? [])]
|
|
753
|
+
: [];
|
|
688
754
|
if (notInjected.length > 0) {
|
|
689
755
|
logger_1.engineLogger.warn('Extracted strings not wired into code', { count: notInjected.length });
|
|
690
756
|
}
|
|
691
757
|
// Format injection: replace hardcoded dates/currencies with Intl.* API calls
|
|
692
|
-
if (frameworkConfig.phases.includes('format-inject') && config.formatConfig?.enabled && formatStrings && formatStrings.length > 0) {
|
|
758
|
+
if (!adoptedSetup && frameworkConfig.phases.includes('format-inject') && config.formatConfig?.enabled && formatStrings && formatStrings.length > 0) {
|
|
693
759
|
config.onProgress?.('Injecting Intl.* format replacements...', 'injection', 'running');
|
|
694
760
|
const formatInjection = await (0, format_injection_1.injectFormats)(workspace, formatStrings, config.formatConfig, config.dryRun);
|
|
695
761
|
if (formatInjection.totalInjections > 0) {
|
|
@@ -703,7 +769,9 @@ async function finalizePipeline(params) {
|
|
|
703
769
|
});
|
|
704
770
|
}
|
|
705
771
|
// gettext: merge this run's translations into the project's .po files.
|
|
706
|
-
const finalizationNotes =
|
|
772
|
+
const finalizationNotes = adoptedSetup
|
|
773
|
+
? (0, adopted_1.adoptedSetupNotes)(workspace, config.sourceLocale, config.targetLocales, extraction.notInjected ?? [])
|
|
774
|
+
: [];
|
|
707
775
|
if (gettext) {
|
|
708
776
|
gettext.refreshReferences(injection);
|
|
709
777
|
const written = await gettext.write(config.targetLocales, allTranslatedPerLocale, {
|
|
@@ -714,7 +782,7 @@ async function finalizePipeline(params) {
|
|
|
714
782
|
finalizationNotes.push(...written.notes);
|
|
715
783
|
}
|
|
716
784
|
// Finalization: install i18n deps, create config files, modify entry points
|
|
717
|
-
if (frameworkConfig.phases.includes('finalize')) {
|
|
785
|
+
if (!adoptedSetup && frameworkConfig.phases.includes('finalize')) {
|
|
718
786
|
config.onProgress?.('Finalizing project...', 'finalization', 'running');
|
|
719
787
|
const { finalization } = await (0, finalization_1.finalizeProject)(workspace, config.dryRun, {
|
|
720
788
|
targetLocales: config.targetLocales,
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import type { ByokProvider, FormatLocaleConfig, Framework } from '@babelize/types';
|
|
9
9
|
import type { EngineProviders, TranslationFailure } from '../providers/types';
|
|
10
10
|
import type { EngineLogger } from '../utils/logger';
|
|
11
|
+
import type { I18nLibraryId } from '../detection/i18n';
|
|
11
12
|
export interface EngineConfigV2 {
|
|
12
13
|
/** Path to the workspace directory */
|
|
13
14
|
workspacePath: string;
|
|
@@ -89,6 +90,16 @@ export interface EngineConfigV2 {
|
|
|
89
90
|
wrapMixedContent?: boolean;
|
|
90
91
|
};
|
|
91
92
|
}
|
|
93
|
+
export interface ExistingI18nSetup {
|
|
94
|
+
library: I18nLibraryId;
|
|
95
|
+
/** Directory of the flat `<locale>.json` files, relative to the workspace (posix). */
|
|
96
|
+
localeDir: string;
|
|
97
|
+
/**
|
|
98
|
+
* Code files that list the app's languages by code (a locale registry, a
|
|
99
|
+
* `supportedLocales` array): a new language may need adding there too.
|
|
100
|
+
*/
|
|
101
|
+
languageLists: string[];
|
|
102
|
+
}
|
|
92
103
|
export interface WorkspaceInfo {
|
|
93
104
|
path: string;
|
|
94
105
|
framework: Framework;
|
|
@@ -120,6 +131,13 @@ export interface WorkspaceInfo {
|
|
|
120
131
|
injectSwitcher?: boolean;
|
|
121
132
|
wrapMixedContent?: boolean;
|
|
122
133
|
};
|
|
134
|
+
/**
|
|
135
|
+
* The app's own i18n setup (vue-i18n with frontend/locales/, next-intl with
|
|
136
|
+
* messages/, …), adopted instead of generating a second one: locale files
|
|
137
|
+
* are read from and written to `localeDir`, the source file is never
|
|
138
|
+
* rewritten, and extraction, injection and finalization don't change code.
|
|
139
|
+
*/
|
|
140
|
+
existingSetup?: ExistingI18nSetup;
|
|
123
141
|
}
|
|
124
142
|
/**
|
|
125
143
|
* Frameworks that the engine pipeline will actively process.
|
|
@@ -228,8 +246,9 @@ export interface LocaleFile {
|
|
|
228
246
|
*/
|
|
229
247
|
content?: string;
|
|
230
248
|
/**
|
|
231
|
-
*
|
|
232
|
-
* project: the code itself is the catalogue)
|
|
249
|
+
* Hosts write nothing for this locale: there is no file (the source
|
|
250
|
+
* language of a gettext project: the code itself is the catalogue), or it
|
|
251
|
+
* is the source file of an adopted i18n setup, which a run never rewrites.
|
|
233
252
|
*/
|
|
234
253
|
noFile?: boolean;
|
|
235
254
|
/** Further files generated for this locale (e.g. a compiled .mo next to the .po). */
|
|
@@ -478,6 +478,15 @@ function isNonTranslatableContext(path) {
|
|
|
478
478
|
(t.isStringLiteral(propKey) && TECH_OBJ_KEYS.has(propKey.value))) {
|
|
479
479
|
return true;
|
|
480
480
|
}
|
|
481
|
+
// HTTP headers: `{ Authorization: `Bearer ${key}` }`, `headers: { Prefer: 'return=minimal' }`.
|
|
482
|
+
// A translated header value breaks the request.
|
|
483
|
+
if (isHttpHeaderName(propertyName(propKey)))
|
|
484
|
+
return true;
|
|
485
|
+
const owner = current.parentPath?.parentPath;
|
|
486
|
+
if (owner?.isObjectProperty() && propertyName(owner.node.key)?.toLowerCase() === 'headers')
|
|
487
|
+
return true;
|
|
488
|
+
if (owner?.isNewExpression() && t.isIdentifier(owner.node.callee, { name: 'Headers' }))
|
|
489
|
+
return true;
|
|
481
490
|
}
|
|
482
491
|
// An object key, also when picked by a ternary or fallback:
|
|
483
492
|
// `Colors[scheme === 'unspecified' ? 'light' : scheme]`, `map[key ?? 'default']`.
|
|
@@ -534,6 +543,25 @@ function isNonTranslatableContext(path) {
|
|
|
534
543
|
}
|
|
535
544
|
return false;
|
|
536
545
|
}
|
|
546
|
+
const HTTP_HEADER_NAMES = new Set([
|
|
547
|
+
'authorization', 'proxy-authorization', 'content-type', 'content-length', 'content-encoding', 'content-disposition',
|
|
548
|
+
'accept', 'accept-encoding', 'accept-language', 'cache-control', 'cookie', 'set-cookie', 'user-agent',
|
|
549
|
+
'origin', 'referer', 'prefer', 'apikey', 'api-key', 'if-none-match', 'if-match', 'etag', 'location',
|
|
550
|
+
]);
|
|
551
|
+
function propertyName(key) {
|
|
552
|
+
if (t.isIdentifier(key))
|
|
553
|
+
return key.name;
|
|
554
|
+
if (t.isStringLiteral(key))
|
|
555
|
+
return key.value;
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
/** `Authorization`, `'Content-Type'`, `'x-api-key'`: a request/response header name. */
|
|
559
|
+
function isHttpHeaderName(name) {
|
|
560
|
+
if (!name)
|
|
561
|
+
return false;
|
|
562
|
+
const lower = name.toLowerCase();
|
|
563
|
+
return HTTP_HEADER_NAMES.has(lower) || /^x-[a-z0-9-]+$/.test(lower);
|
|
564
|
+
}
|
|
537
565
|
/**
|
|
538
566
|
* Expressions a value passes through unchanged on its way to its slot:
|
|
539
567
|
* `a ? 'x' : b`, `k ?? 'x'`, `('x' as K)`, `x!`.
|
|
@@ -11,9 +11,23 @@ export declare function localeExtension(format: string): string;
|
|
|
11
11
|
/**
|
|
12
12
|
* Compute the locale directory and file path for a given target locale.
|
|
13
13
|
* Django uses `locale/<lang>/LC_MESSAGES/django.po`,
|
|
14
|
-
* other frameworks use `<publicDir>/locales/<lang>.json
|
|
14
|
+
* other frameworks use `<publicDir>/locales/<lang>.json`, or
|
|
15
|
+
* `<existingLocaleDir>/<lang>.json` when the app's own i18n setup was adopted.
|
|
15
16
|
*/
|
|
16
|
-
export declare function localeFilePath(workspacePath: string, publicDir: string, localeFormat: string, targetLocale: string): {
|
|
17
|
+
export declare function localeFilePath(workspacePath: string, publicDir: string, localeFormat: string, targetLocale: string, existingLocaleDir?: string): {
|
|
18
|
+
dir: string;
|
|
19
|
+
file: string;
|
|
20
|
+
relativeFile: string;
|
|
21
|
+
};
|
|
22
|
+
/** localeFilePath() for a validated workspace (honours an adopted i18n setup). */
|
|
23
|
+
export declare function workspaceLocaleFile(workspace: {
|
|
24
|
+
path: string;
|
|
25
|
+
publicDir: string;
|
|
26
|
+
localeFormat: string;
|
|
27
|
+
existingSetup?: {
|
|
28
|
+
localeDir: string;
|
|
29
|
+
};
|
|
30
|
+
}, locale: string): {
|
|
17
31
|
dir: string;
|
|
18
32
|
file: string;
|
|
19
33
|
relativeFile: string;
|
package/dist/utils/file-utils.js
CHANGED
|
@@ -44,6 +44,7 @@ exports.readJsonFile = readJsonFile;
|
|
|
44
44
|
exports.writeJsonFile = writeJsonFile;
|
|
45
45
|
exports.localeExtension = localeExtension;
|
|
46
46
|
exports.localeFilePath = localeFilePath;
|
|
47
|
+
exports.workspaceLocaleFile = workspaceLocaleFile;
|
|
47
48
|
exports.ensureDir = ensureDir;
|
|
48
49
|
exports.copyFile = copyFile;
|
|
49
50
|
exports.deleteFile = deleteFile;
|
|
@@ -203,9 +204,10 @@ function localeExtension(format) {
|
|
|
203
204
|
/**
|
|
204
205
|
* Compute the locale directory and file path for a given target locale.
|
|
205
206
|
* Django uses `locale/<lang>/LC_MESSAGES/django.po`,
|
|
206
|
-
* other frameworks use `<publicDir>/locales/<lang>.json
|
|
207
|
+
* other frameworks use `<publicDir>/locales/<lang>.json`, or
|
|
208
|
+
* `<existingLocaleDir>/<lang>.json` when the app's own i18n setup was adopted.
|
|
207
209
|
*/
|
|
208
|
-
function localeFilePath(workspacePath, publicDir, localeFormat, targetLocale) {
|
|
210
|
+
function localeFilePath(workspacePath, publicDir, localeFormat, targetLocale, existingLocaleDir) {
|
|
209
211
|
if (localeFormat === 'po') {
|
|
210
212
|
// publicDir is the locale directory (LOCALE_PATHS) for gettext projects;
|
|
211
213
|
// Django names locale directories pt_BR, zh_Hans, …
|
|
@@ -217,11 +219,16 @@ function localeFilePath(workspacePath, publicDir, localeFormat, targetLocale) {
|
|
|
217
219
|
return { dir, file, relativeFile };
|
|
218
220
|
}
|
|
219
221
|
const ext = localeExtension(localeFormat);
|
|
220
|
-
const
|
|
222
|
+
const relativeDir = existingLocaleDir ?? path.join(publicDir, 'locales');
|
|
223
|
+
const dir = path.join(workspacePath, relativeDir);
|
|
221
224
|
const file = path.join(dir, `${targetLocale}${ext}`);
|
|
222
|
-
const relativeFile = path.join(
|
|
225
|
+
const relativeFile = path.join(relativeDir, `${targetLocale}${ext}`);
|
|
223
226
|
return { dir, file, relativeFile };
|
|
224
227
|
}
|
|
228
|
+
/** localeFilePath() for a validated workspace (honours an adopted i18n setup). */
|
|
229
|
+
function workspaceLocaleFile(workspace, locale) {
|
|
230
|
+
return localeFilePath(workspace.path, workspace.publicDir, workspace.localeFormat, locale, workspace.existingSetup?.localeDir);
|
|
231
|
+
}
|
|
225
232
|
async function ensureDir(dirPath) {
|
|
226
233
|
await fs.promises.mkdir(dirPath, { recursive: true });
|
|
227
234
|
}
|
package/package.json
CHANGED