@babelize/engine 0.3.8 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/analysis/analyze.d.ts +3 -0
- package/dist/analysis/analyze.js +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -1
- package/dist/local/translate-core.d.ts +6 -0
- package/dist/local/translate-core.js +1 -0
- package/dist/modules/extractor/extract.js +22 -5
- package/dist/modules/finalization/finalize.d.ts +6 -0
- package/dist/modules/finalization/finalize.js +25 -5
- package/dist/modules/finalization/nextjs-finalize.d.ts +44 -4
- package/dist/modules/finalization/nextjs-finalize.js +294 -23
- package/dist/modules/format-injection/index.js +3 -2
- package/dist/modules/injection/inject.js +2 -1
- package/dist/modules/sync-detector/sync-detector.js +4 -1
- package/dist/modules/workspace/validate.js +7 -0
- package/dist/runtime/types.d.ts +8 -0
- package/dist/utils/ast-helpers.js +35 -4
- package/dist/utils/source-scope.d.ts +30 -0
- package/dist/utils/source-scope.js +112 -0
- package/dist/utils/ui-copy.d.ts +14 -0
- package/dist/utils/ui-copy.js +51 -0
- package/package.json +3 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtractedString } from '../runtime/types';
|
|
2
|
+
import type { SourceScope } from '../utils/source-scope';
|
|
2
3
|
export type FrameworkSupport = 'supported' | 'beta' | 'unsupported';
|
|
3
4
|
/** How well `babelize translate` handles a detected framework. */
|
|
4
5
|
export declare function frameworkSupport(framework: string): FrameworkSupport;
|
|
@@ -95,6 +96,8 @@ export interface AnalyzeOptions {
|
|
|
95
96
|
targetLocales?: string[];
|
|
96
97
|
/** Parent dir for the temp copy (default: OS temp dir). */
|
|
97
98
|
tmpRoot?: string;
|
|
99
|
+
/** Source files to analyze; each list given replaces `.babelize/config.json` `include`/`exclude`. */
|
|
100
|
+
sourceScope?: SourceScope;
|
|
98
101
|
}
|
|
99
102
|
/** Analyze `projectDir` on a temp copy; the project itself is only read. */
|
|
100
103
|
export declare function analyzeProject(projectDir: string, options?: AnalyzeOptions): Promise<ProjectAnalysis>;
|
package/dist/analysis/analyze.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -61,4 +61,6 @@ export type { LocaleChangeReview, LocaleSetChangeReview, ReviewOptions } from '.
|
|
|
61
61
|
export { checkProjectLocales, localeIssueFile, readProjectLocaleConfig } from './qa/check-project';
|
|
62
62
|
export type { CheckProjectOptions, LocaleSetReport, ProjectLocaleCheck, ProjectLocaleConfig } from './qa/check-project';
|
|
63
63
|
export { hashText, translationCacheKey, TRANSLATION_CACHE_TTL_SECONDS } from './utils/cache-keys';
|
|
64
|
+
export { createScopeMatcher, mergeSourceScope, normalizeScopePatterns, readSourceScope } from './utils/source-scope';
|
|
65
|
+
export type { SourceScope } from './utils/source-scope';
|
|
64
66
|
export * from './local';
|
package/dist/index.js
CHANGED
|
@@ -22,7 +22,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
22
22
|
};
|
|
23
23
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
24
|
exports.CircuitBreaker = exports.validateBatchQuality = exports.validateTranslationQuality = exports.translatorLoadBalancer = exports.warmupTranslator = exports.checkTranslatorHealth = exports.callTranslator = exports.requiredPluralCategories = exports.parseIcu = exports.isIcuMessage = exports.compareIcuMessages = exports.sameProtectedSpans = exports.restoreText = exports.protectText = exports.hasNothingToTranslate = exports.checkTokens = exports.validateRawTokens = exports.sanitizeTranslation = exports.restorePlaceholders = exports.protectPlaceholders = exports.hashString = exports.hasICUSyntax = exports.extractPlaceholders = exports.parseCode = exports.I18N_LIBRARY_NAMES = exports.detectI18n = exports.SUPPORTED_SUMMARY = exports.FRAMEWORK_DISPLAY_NAMES = exports.localRepoFiles = exports.detectStack = exports.saveProjectConfig = exports.saveCachedStrings = exports.getProjectInfo = exports.getBabelizeSummary = exports.detectProjectInfo = exports.addBabelToHistory = exports.formatSyncNotificationMessage = exports.detectSyncIssues = exports.matchFromMemory = exports.setLocaleValue = exports.applyTranslationOverrides = exports.setEngineLogger = exports.runWithEngineLogger = exports.validateWorkspace = exports.scanKeyReferences = exports.RunAbortedError = exports.validateEngineConfigV2 = exports.runEngineV2 = exports.loadBabelizeConfig = exports.BabelizeEngine = void 0;
|
|
25
|
-
exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
|
|
25
|
+
exports.readSourceScope = exports.normalizeScopePatterns = exports.mergeSourceScope = exports.createScopeMatcher = exports.TRANSLATION_CACHE_TTL_SECONDS = exports.translationCacheKey = exports.hashText = exports.readProjectLocaleConfig = exports.localeIssueFile = exports.checkProjectLocales = exports.ReviewError = exports.reviewLocaleChanges = exports.loadLocale = exports.isLocaleCode = exports.isIgnoredLocalePath = exports.groupLocaleFiles = exports.findLocaleFileSets = exports.DEFAULT_LOCALE_IGNORE_DIRS = exports.sanitizeFormality = exports.parseFormalityList = exports.hasFormalitySplit = exports.formalityOf = exports.formalityIssues = exports.formalityInstruction = exports.formalityFor = exports.detectFormality = exports.glossaryFingerprint = exports.normalizeGlossary = exports.localeValue = exports.containsTerm = exports.canonicalizeLocaleKeys = exports.canonicalLocale = exports.tallyLocaleIssues = exports.flattenLocaleMessages = exports.checkLocalePair = exports.frameworkSupport = exports.analyzeWorkspace = exports.analyzeProject = exports.localeExtension = exports.getCircuitBreaker = exports.CircuitState = void 0;
|
|
26
26
|
var BabelizeEngine_1 = require("./BabelizeEngine");
|
|
27
27
|
Object.defineProperty(exports, "BabelizeEngine", { enumerable: true, get: function () { return BabelizeEngine_1.BabelizeEngine; } });
|
|
28
28
|
var config_1 = require("./config");
|
|
@@ -153,5 +153,10 @@ var cache_keys_1 = require("./utils/cache-keys");
|
|
|
153
153
|
Object.defineProperty(exports, "hashText", { enumerable: true, get: function () { return cache_keys_1.hashText; } });
|
|
154
154
|
Object.defineProperty(exports, "translationCacheKey", { enumerable: true, get: function () { return cache_keys_1.translationCacheKey; } });
|
|
155
155
|
Object.defineProperty(exports, "TRANSLATION_CACHE_TTL_SECONDS", { enumerable: true, get: function () { return cache_keys_1.TRANSLATION_CACHE_TTL_SECONDS; } });
|
|
156
|
+
var source_scope_1 = require("./utils/source-scope");
|
|
157
|
+
Object.defineProperty(exports, "createScopeMatcher", { enumerable: true, get: function () { return source_scope_1.createScopeMatcher; } });
|
|
158
|
+
Object.defineProperty(exports, "mergeSourceScope", { enumerable: true, get: function () { return source_scope_1.mergeSourceScope; } });
|
|
159
|
+
Object.defineProperty(exports, "normalizeScopePatterns", { enumerable: true, get: function () { return source_scope_1.normalizeScopePatterns; } });
|
|
160
|
+
Object.defineProperty(exports, "readSourceScope", { enumerable: true, get: function () { return source_scope_1.readSourceScope; } });
|
|
156
161
|
// ── Local translation runner (CLI `babelize translate`, MCP `babelize_translate`) ──
|
|
157
162
|
__exportStar(require("./local"), exports);
|
|
@@ -2,6 +2,7 @@ import type { EngineConfigV2, EngineResultV2 } from '../runtime/types';
|
|
|
2
2
|
import type { ProjectRulesStore, TranslationFailure, TranslationProvider } from '../providers/types';
|
|
3
3
|
import type { LocaleGlossary } from '../qa/locale-qa';
|
|
4
4
|
import type { FormalitySetting } from '../modules/translator/formality';
|
|
5
|
+
import type { SourceScope } from '../utils/source-scope';
|
|
5
6
|
/** A rules store serving `.babelize/config.json` rules: glossary, brand voice and formality. */
|
|
6
7
|
export declare function configRulesStore(glossary: LocaleGlossary | undefined, extra?: {
|
|
7
8
|
brandVoice?: string;
|
|
@@ -43,6 +44,11 @@ export interface LocalTranslateOptions {
|
|
|
43
44
|
formality?: Record<string, FormalitySetting>;
|
|
44
45
|
/** Tone and style for the translator; replaces `.babelize/config.json` `brandVoice`. */
|
|
45
46
|
brandVoice?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Source files to extract from and rewrite (`--include`/`--exclude` globs).
|
|
49
|
+
* Each list given replaces `.babelize/config.json` `include`/`exclude`.
|
|
50
|
+
*/
|
|
51
|
+
sourceScope?: SourceScope;
|
|
46
52
|
}
|
|
47
53
|
export interface LocalTranslateDeps {
|
|
48
54
|
/** Replaces the BYOK translator (tests). */
|
|
@@ -359,6 +359,7 @@ async function runScoped(opts, deps, engineLog, state) {
|
|
|
359
359
|
// and the updated one comes back with the other changes — only on success.
|
|
360
360
|
dataDir: temp.dir,
|
|
361
361
|
byok: translator ? undefined : opts.byok,
|
|
362
|
+
...(opts.sourceScope ? { sourceScope: opts.sourceScope } : {}),
|
|
362
363
|
providers: translator || rules ? { ...(translator ? { translator } : {}), ...(rules ? { rules } : {}) } : undefined,
|
|
363
364
|
installDependencies: false,
|
|
364
365
|
onProgress: (message, step, status) => deps.onProgress?.(message, step, status),
|
|
@@ -49,6 +49,7 @@ const jsx_message_1 = require("../../utils/jsx-message");
|
|
|
49
49
|
const ui_copy_1 = require("../../utils/ui-copy");
|
|
50
50
|
const module_constants_1 = require("../../utils/module-constants");
|
|
51
51
|
const react_native_1 = require("../../utils/react-native");
|
|
52
|
+
const source_scope_1 = require("../../utils/source-scope");
|
|
52
53
|
/** Frameworks whose injection strategies can render a JSX sentence as one message. */
|
|
53
54
|
const SENTENCE_FRAMEWORKS = new Set(['react', 'nextjs', 'react-native']);
|
|
54
55
|
async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
|
|
@@ -60,10 +61,8 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
|
|
|
60
61
|
const notInjected = [];
|
|
61
62
|
const sourceFiles = [];
|
|
62
63
|
if (filesToProcess && filesToProcess.length > 0) {
|
|
63
|
-
// If specific files are provided, only scan those
|
|
64
|
-
|
|
65
|
-
sourceFiles.push(path.join(workspace.path, relPath));
|
|
66
|
-
}
|
|
64
|
+
// If specific files are provided, only scan those (still within the project's scope)
|
|
65
|
+
sourceFiles.push(...(0, source_scope_1.filterToScope)(workspace, filesToProcess.map((relPath) => path.join(workspace.path, relPath))));
|
|
67
66
|
}
|
|
68
67
|
else {
|
|
69
68
|
// Otherwise scan all source directories. Root-scanning frameworks use
|
|
@@ -74,7 +73,7 @@ async function extractStrings(workspace, filesToProcess, extractOptions = {}) {
|
|
|
74
73
|
const excluded = (0, types_1.workspaceExcludes)(workspace);
|
|
75
74
|
for (const sourceDir of workspace.sourceDirs) {
|
|
76
75
|
const dirPath = path.join(workspace.path, sourceDir);
|
|
77
|
-
const files = await (0, file_utils_1.findFiles)(dirPath, extensions, excluded);
|
|
76
|
+
const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, excluded));
|
|
78
77
|
sourceFiles.push(...files);
|
|
79
78
|
}
|
|
80
79
|
}
|
|
@@ -182,6 +181,20 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
182
181
|
const isTypeScript = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
|
|
183
182
|
try {
|
|
184
183
|
const ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript });
|
|
184
|
+
// Options of this file's string-literal union types: never copy (#379).
|
|
185
|
+
const unionMembers = isTypeScript ? (0, ui_copy_1.literalUnionMembers)(ast) : new Set();
|
|
186
|
+
/**
|
|
187
|
+
* A string literal that picks a value rather than showing one: text
|
|
188
|
+
* direction, a union option, or a component prop option (#379).
|
|
189
|
+
*/
|
|
190
|
+
const isOptionValue = (path, text) => {
|
|
191
|
+
if (!path.isStringLiteral?.())
|
|
192
|
+
return false;
|
|
193
|
+
if ((0, ui_copy_1.isDirectionValue)(text) || unionMembers.has(text))
|
|
194
|
+
return true;
|
|
195
|
+
const attribute = path.parentPath;
|
|
196
|
+
return !!attribute?.isJSXAttribute() && (0, ui_copy_1.isComponentOptionValue)(attribute.node, attribute.parentPath.node, text);
|
|
197
|
+
};
|
|
185
198
|
// UI copy in module-level constants rendered by components (#248): keys
|
|
186
199
|
// when every use is a render, otherwise reported — never silently skipped.
|
|
187
200
|
if (!options?.framework || SENTENCE_FRAMEWORKS.has(options.framework)) {
|
|
@@ -240,6 +253,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
240
253
|
return;
|
|
241
254
|
if (/^\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?$/.test(text))
|
|
242
255
|
return;
|
|
256
|
+
if (isOptionValue(path, text))
|
|
257
|
+
return;
|
|
243
258
|
// A literal in a branch (`role === 'brand' ? 'brand' : 'creator'`, `user?.id ?? 'usr_1'`)
|
|
244
259
|
// goes where the whole expression goes, so that's where it's judged.
|
|
245
260
|
const site = valueSite(path);
|
|
@@ -465,6 +480,8 @@ async function extractStringsFromFile(content, filePath, detectFormats, options)
|
|
|
465
480
|
return;
|
|
466
481
|
if ((0, ast_helpers_1.isAlreadyTranslated)(path.node, path))
|
|
467
482
|
return;
|
|
483
|
+
if (isOptionValue(path.get('value'), text))
|
|
484
|
+
return;
|
|
468
485
|
const id = `${filePath}:${path.node.loc?.start.line}:${(0, string_utils_1.hashString)(text)}`;
|
|
469
486
|
noteOffset(id, path.node.start);
|
|
470
487
|
if (!seenTexts.has(id)) {
|
|
@@ -5,6 +5,12 @@ interface PackageJson {
|
|
|
5
5
|
devDependencies?: Record<string, string>;
|
|
6
6
|
[key: string]: unknown;
|
|
7
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* Whether package.json describes a package published to npm (not an app):
|
|
10
|
+
* not private, with library entry points or a files list. `main` alone isn't
|
|
11
|
+
* enough: Expo, Electron and Node apps use it for their own entry.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isPublishedPackage(pkg: PackageJson): boolean;
|
|
8
14
|
export declare function finalizeProject(workspace: WorkspaceInfo, dryRun: boolean, options?: {
|
|
9
15
|
targetLocales?: string[];
|
|
10
16
|
sourceLocale?: string;
|
|
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.isPublishedPackage = isPublishedPackage;
|
|
36
37
|
exports.finalizeProject = finalizeProject;
|
|
37
38
|
exports.i18nRuntimeFor = i18nRuntimeFor;
|
|
38
39
|
const path = __importStar(require("path"));
|
|
@@ -49,6 +50,16 @@ const react_native_finalize_1 = require("./react-native-finalize");
|
|
|
49
50
|
const dependencies_1 = require("./dependencies");
|
|
50
51
|
const i18n_config_path_1 = require("../../utils/i18n-config-path");
|
|
51
52
|
const i18next_icu_1 = require("../../utils/i18next-icu");
|
|
53
|
+
/**
|
|
54
|
+
* Whether package.json describes a package published to npm (not an app):
|
|
55
|
+
* not private, with library entry points or a files list. `main` alone isn't
|
|
56
|
+
* enough: Expo, Electron and Node apps use it for their own entry.
|
|
57
|
+
*/
|
|
58
|
+
function isPublishedPackage(pkg) {
|
|
59
|
+
if (pkg.private === true)
|
|
60
|
+
return false;
|
|
61
|
+
return ['exports', 'module', 'types', 'typings', 'files', 'publishConfig'].some((field) => pkg[field] !== undefined);
|
|
62
|
+
}
|
|
52
63
|
const DEPENDENCIES_BY_FRAMEWORK = {
|
|
53
64
|
react: dependencies_1.I18NEXT_WEB_DEPENDENCIES,
|
|
54
65
|
// Next.js projects that already use react-i18next keep it (injection picks
|
|
@@ -254,15 +265,22 @@ async function finalizeProject(workspace, dryRun, options = {}) {
|
|
|
254
265
|
if (rn.warning)
|
|
255
266
|
warnings.push(rn.warning);
|
|
256
267
|
}
|
|
257
|
-
|
|
268
|
+
// A package.json that is also a published library (a component kit with
|
|
269
|
+
// its docs site in the same package) would ship the site's i18n runtime
|
|
270
|
+
// to every consumer: it goes in devDependencies there (#378).
|
|
271
|
+
const field = isPublishedPackage(pkg) ? 'devDependencies' : 'dependencies';
|
|
272
|
+
const missingDeps = Object.keys(requiredDeps).filter((d) => !deps[d] && !(field === 'devDependencies' && pkg.devDependencies?.[d]));
|
|
258
273
|
if (missingDeps.length > 0) {
|
|
259
|
-
|
|
274
|
+
const target = { ...pkg[field] };
|
|
260
275
|
for (const dep of missingDeps) {
|
|
261
|
-
|
|
276
|
+
target[dep] = requiredDeps[dep];
|
|
262
277
|
}
|
|
263
278
|
// Keep the user's key order (a sorted package.json is an unreviewable
|
|
264
279
|
// diff); only the dependency map is sorted, as npm does.
|
|
265
|
-
pkg
|
|
280
|
+
pkg[field] = Object.fromEntries(Object.entries(target).sort(([a], [b]) => a.localeCompare(b)));
|
|
281
|
+
if (field === 'devDependencies') {
|
|
282
|
+
warnings.push(`package.json is a published package, so ${missingDeps.join(', ')} went into devDependencies to keep ${missingDeps.length === 1 ? 'it' : 'them'} out of your consumers' installs.`);
|
|
283
|
+
}
|
|
266
284
|
await writer.write(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
|
267
285
|
if (!dryRun) {
|
|
268
286
|
// A committed lockfile must move with package.json, or `npm ci` /
|
|
@@ -745,5 +763,7 @@ function i18nRuntimeFor(framework, pkg) {
|
|
|
745
763
|
: fw === 'react-native' ? (0, react_native_finalize_1.reactNativeDependencies)(pkg ?? undefined).deps
|
|
746
764
|
: DEPENDENCIES_BY_FRAMEWORK[fw] ?? {});
|
|
747
765
|
const library = nextIntl ? 'next-intl' : fw === 'vue' ? 'vue-i18n' : 'react-i18next';
|
|
748
|
-
|
|
766
|
+
// A published package keeps them in devDependencies (see finalizeWorkspace).
|
|
767
|
+
const installed = pkg && isPublishedPackage(pkg) ? deps : pkg?.dependencies ?? {};
|
|
768
|
+
return { library, required, missing: required.filter((d) => !installed[d]) };
|
|
749
769
|
}
|
|
@@ -6,28 +6,68 @@ import type { WorkspaceInfo } from '../../runtime/types';
|
|
|
6
6
|
* Injection rewrites Next.js components to next-intl (`getTranslations` in
|
|
7
7
|
* Server Components, `useTranslations` in Client Components — see
|
|
8
8
|
* NextIntlStrategy), so the project must be wired for next-intl or every
|
|
9
|
-
* page throws at runtime.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
9
|
+
* page throws at runtime. Each language gets its own URL without moving any
|
|
10
|
+
* route (#380): a generated proxy (middleware before Next 16) serves
|
|
11
|
+
* `/ja/docs` from the existing `app/docs` route and tells next-intl the
|
|
12
|
+
* locale in a request header. The source language stays unprefixed, a
|
|
13
|
+
* NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
|
|
14
|
+
* its translations to search engines with hreflang `Link` headers. The root
|
|
15
|
+
* layout's <html> gets the locale's `lang` and `dir`. Messages are the
|
|
16
|
+
* generated `public/locales/<locale>.json` files.
|
|
17
|
+
*
|
|
18
|
+
* `"routing": "cookie"` in .babelize/config.json keeps one URL for every
|
|
19
|
+
* language (the locale comes from the cookie or Accept-Language).
|
|
13
20
|
*
|
|
14
21
|
* Every edit is a minimal text splice (the user's formatting is kept), and
|
|
15
22
|
* anything that can't be wired automatically becomes a warning — never a
|
|
16
23
|
* silently half-configured project.
|
|
17
24
|
*/
|
|
18
25
|
export declare const NEXT_INTL_DEPENDENCIES: Record<string, string>;
|
|
26
|
+
/** Request header the proxy sets with the URL's locale. */
|
|
27
|
+
export declare const LOCALE_HEADER = "x-babelize-locale";
|
|
28
|
+
export type NextRouting = 'prefix' | 'cookie';
|
|
19
29
|
export interface NextIntlFinalizeResult {
|
|
20
30
|
configFileCreated: boolean;
|
|
21
31
|
entryPointModified: boolean;
|
|
22
32
|
warnings: string[];
|
|
23
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* `i18n/locales`: the locale list and text direction, shared by the request
|
|
36
|
+
* config, the proxy and the root layout. Plain data, safe to import anywhere.
|
|
37
|
+
*/
|
|
38
|
+
export declare function buildLocalesModule(opts: {
|
|
39
|
+
sourceLocale: string;
|
|
40
|
+
locales: string[];
|
|
41
|
+
typescript: boolean;
|
|
42
|
+
}): string;
|
|
24
43
|
export declare function buildRequestConfig(opts: {
|
|
25
44
|
sourceLocale: string;
|
|
26
45
|
locales: string[];
|
|
27
46
|
/** Import path from the request config file to a locale file, with `__LOCALE__` as placeholder. */
|
|
28
47
|
messagesImportPath: string;
|
|
29
48
|
typescript: boolean;
|
|
49
|
+
/** `prefix`: the proxy's locale header wins. Default `cookie` (no proxy). */
|
|
50
|
+
routing?: NextRouting;
|
|
30
51
|
}): string;
|
|
52
|
+
/**
|
|
53
|
+
* The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
|
|
54
|
+
* locale in a request header; the source language has no prefix. A visitor
|
|
55
|
+
* who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
|
|
56
|
+
* lists its translations in hreflang `Link` headers.
|
|
57
|
+
*/
|
|
58
|
+
export declare function buildProxy(opts: {
|
|
59
|
+
kind: 'proxy' | 'middleware';
|
|
60
|
+
typescript: boolean;
|
|
61
|
+
}): string;
|
|
62
|
+
/**
|
|
63
|
+
* Give the root layout's <html> the active locale's `lang` and `dir`
|
|
64
|
+
* (#380): `const locale = useLocale()` in the default-exported layout
|
|
65
|
+
* (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
|
|
66
|
+
* can edit safely (no <html>, an expression-bodied arrow, no default export).
|
|
67
|
+
*/
|
|
68
|
+
export declare function setHtmlLocale(content: string, typescript: boolean, localesImport: string): string | null;
|
|
69
|
+
/** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
|
|
70
|
+
export declare function nextMajor(packageJson: Record<string, any> | undefined): number | null;
|
|
31
71
|
/** Wrap the next.config default export / module.exports with next-intl's plugin. */
|
|
32
72
|
export declare function wrapNextConfig(content: string, requestConfigPath: string, typescript: boolean): string | null;
|
|
33
73
|
/**
|
|
@@ -33,8 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.NEXT_INTL_DEPENDENCIES = void 0;
|
|
36
|
+
exports.LOCALE_HEADER = exports.NEXT_INTL_DEPENDENCIES = void 0;
|
|
37
|
+
exports.buildLocalesModule = buildLocalesModule;
|
|
37
38
|
exports.buildRequestConfig = buildRequestConfig;
|
|
39
|
+
exports.buildProxy = buildProxy;
|
|
40
|
+
exports.setHtmlLocale = setHtmlLocale;
|
|
41
|
+
exports.nextMajor = nextMajor;
|
|
38
42
|
exports.wrapNextConfig = wrapNextConfig;
|
|
39
43
|
exports.usesCacheComponents = usesCacheComponents;
|
|
40
44
|
exports.wrapRootLayout = wrapRootLayout;
|
|
@@ -44,16 +48,24 @@ const path = __importStar(require("path"));
|
|
|
44
48
|
const file_utils_1 = require("../../utils/file-utils");
|
|
45
49
|
const writes_1 = require("./writes");
|
|
46
50
|
const ast_helpers_1 = require("../../utils/ast-helpers");
|
|
51
|
+
const rtl_languages_1 = require("../translator/language-codes/rtl-languages");
|
|
47
52
|
/**
|
|
48
53
|
* Next.js finalization for next-intl.
|
|
49
54
|
*
|
|
50
55
|
* Injection rewrites Next.js components to next-intl (`getTranslations` in
|
|
51
56
|
* Server Components, `useTranslations` in Client Components — see
|
|
52
57
|
* NextIntlStrategy), so the project must be wired for next-intl or every
|
|
53
|
-
* page throws at runtime.
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
58
|
+
* page throws at runtime. Each language gets its own URL without moving any
|
|
59
|
+
* route (#380): a generated proxy (middleware before Next 16) serves
|
|
60
|
+
* `/ja/docs` from the existing `app/docs` route and tells next-intl the
|
|
61
|
+
* locale in a request header. The source language stays unprefixed, a
|
|
62
|
+
* NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
|
|
63
|
+
* its translations to search engines with hreflang `Link` headers. The root
|
|
64
|
+
* layout's <html> gets the locale's `lang` and `dir`. Messages are the
|
|
65
|
+
* generated `public/locales/<locale>.json` files.
|
|
66
|
+
*
|
|
67
|
+
* `"routing": "cookie"` in .babelize/config.json keeps one URL for every
|
|
68
|
+
* language (the locale comes from the cookie or Accept-Language).
|
|
57
69
|
*
|
|
58
70
|
* Every edit is a minimal text splice (the user's formatting is kept), and
|
|
59
71
|
* anything that can't be wired automatically becomes a warning — never a
|
|
@@ -63,6 +75,11 @@ exports.NEXT_INTL_DEPENDENCIES = {
|
|
|
63
75
|
'next-intl': '^4.0.0',
|
|
64
76
|
};
|
|
65
77
|
const GENERATED_MARKER = '@babelize-generated next-intl request config';
|
|
78
|
+
const LOCALES_MARKER = '@babelize-generated locale list';
|
|
79
|
+
const PROXY_MARKER = '@babelize-generated locale routing';
|
|
80
|
+
/** Request header the proxy sets with the URL's locale. */
|
|
81
|
+
exports.LOCALE_HEADER = 'x-babelize-locale';
|
|
82
|
+
const PROXY_FILES = ['proxy.ts', 'proxy.js', 'middleware.ts', 'middleware.js'];
|
|
66
83
|
const NEXT_CONFIG_FILES = ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs'];
|
|
67
84
|
const LAYOUT_FILES = ['layout.tsx', 'layout.jsx', 'layout.js', 'layout.ts'];
|
|
68
85
|
function applySplices(content, splices) {
|
|
@@ -99,18 +116,52 @@ async function findFirst(dir, names) {
|
|
|
99
116
|
}
|
|
100
117
|
return null;
|
|
101
118
|
}
|
|
119
|
+
/** `sourceLocale` first, then the rest, without duplicates. */
|
|
120
|
+
function orderedLocales(sourceLocale, locales) {
|
|
121
|
+
return [sourceLocale, ...new Set(locales.filter((l) => l !== sourceLocale))];
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* `i18n/locales`: the locale list and text direction, shared by the request
|
|
125
|
+
* config, the proxy and the root layout. Plain data, safe to import anywhere.
|
|
126
|
+
*/
|
|
127
|
+
function buildLocalesModule(opts) {
|
|
128
|
+
const locales = orderedLocales(opts.sourceLocale, opts.locales);
|
|
129
|
+
const rtl = locales.filter(rtl_languages_1.isRTL);
|
|
130
|
+
const ts = opts.typescript;
|
|
131
|
+
return `// ${LOCALES_MARKER}
|
|
132
|
+
// Babelize regenerates this file while the line above is present.
|
|
133
|
+
export const sourceLocale = ${JSON.stringify(opts.sourceLocale)};
|
|
134
|
+
export const locales = ${JSON.stringify(locales)}${ts ? ' as string[]' : ''};
|
|
135
|
+
|
|
136
|
+
const rightToLeft = ${JSON.stringify(rtl)}${ts ? ' as string[]' : ''};
|
|
137
|
+
|
|
138
|
+
/** \`dir\` for <html>: right-to-left scripts (Arabic, Hebrew, Persian, Urdu…). */
|
|
139
|
+
export function localeDirection(locale${ts ? ': string' : ''})${ts ? ": 'rtl' | 'ltr'" : ''} {
|
|
140
|
+
return rightToLeft.includes(locale) ? 'rtl' : 'ltr';
|
|
141
|
+
}
|
|
142
|
+
`;
|
|
143
|
+
}
|
|
102
144
|
function buildRequestConfig(opts) {
|
|
103
|
-
const locales = [opts.sourceLocale, ...opts.locales.filter((l) => l !== opts.sourceLocale)];
|
|
104
145
|
const ts = opts.typescript;
|
|
105
146
|
const importPath = opts.messagesImportPath.replace('__LOCALE__', '${locale}');
|
|
147
|
+
const routed = opts.routing === 'prefix'
|
|
148
|
+
? ` // The URL's language (/ja/…), from the locale proxy.
|
|
149
|
+
const routed = requestHeaders.get('${exports.LOCALE_HEADER}');
|
|
150
|
+
if (routed && locales.includes(routed)) return { locale: routed, messages: await messagesFor(routed) };
|
|
151
|
+
`
|
|
152
|
+
: '';
|
|
106
153
|
return `// ${GENERATED_MARKER}
|
|
107
154
|
// Babelize regenerates this file (to update the locale list) while the line
|
|
108
155
|
// above is present. Remove that line to take it over.
|
|
109
156
|
import { getRequestConfig } from 'next-intl/server';
|
|
110
157
|
import { cookies, headers } from 'next/headers';
|
|
158
|
+
import { locales, sourceLocale } from './locales';
|
|
111
159
|
|
|
112
|
-
export
|
|
113
|
-
|
|
160
|
+
export { locales, sourceLocale };
|
|
161
|
+
|
|
162
|
+
async function messagesFor(locale${ts ? ': string' : ''}) {
|
|
163
|
+
return (await import(\`${importPath}\`)).default;
|
|
164
|
+
}
|
|
114
165
|
|
|
115
166
|
function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ? ': string' : ''} {
|
|
116
167
|
for (const candidate of candidates) {
|
|
@@ -125,19 +176,185 @@ function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ?
|
|
|
125
176
|
}
|
|
126
177
|
|
|
127
178
|
export default getRequestConfig(async () => {
|
|
128
|
-
|
|
179
|
+
const requestHeaders = await headers();
|
|
180
|
+
${routed} // Otherwise the NEXT_LOCALE cookie, then the browser's Accept-Language.
|
|
129
181
|
const cookieLocale = (await cookies()).get('NEXT_LOCALE')?.value;
|
|
130
|
-
const acceptLanguage = (
|
|
182
|
+
const acceptLanguage = (requestHeaders.get('accept-language') ?? '')
|
|
131
183
|
.split(',')
|
|
132
184
|
.map((part) => part.split(';')[0].trim());
|
|
133
185
|
const locale = pickLocale([cookieLocale, ...acceptLanguage]);
|
|
134
|
-
return {
|
|
135
|
-
locale,
|
|
136
|
-
messages: (await import(\`${importPath}\`)).default,
|
|
137
|
-
};
|
|
186
|
+
return { locale, messages: await messagesFor(locale) };
|
|
138
187
|
});
|
|
139
188
|
`;
|
|
140
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
|
|
192
|
+
* locale in a request header; the source language has no prefix. A visitor
|
|
193
|
+
* who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
|
|
194
|
+
* lists its translations in hreflang `Link` headers.
|
|
195
|
+
*/
|
|
196
|
+
function buildProxy(opts) {
|
|
197
|
+
const ts = opts.typescript;
|
|
198
|
+
const req = ts ? 'request: NextRequest' : 'request';
|
|
199
|
+
return `// ${PROXY_MARKER}
|
|
200
|
+
// Babelize regenerates this file while the line above is present. Remove that
|
|
201
|
+
// line to take it over (keep the ${exports.LOCALE_HEADER} header and the matcher).
|
|
202
|
+
import { NextResponse${ts ? ', type NextRequest' : ''} } from 'next/server';
|
|
203
|
+
import { locales, sourceLocale } from './i18n/locales';
|
|
204
|
+
|
|
205
|
+
const ONE_YEAR = 60 * 60 * 24 * 365;
|
|
206
|
+
|
|
207
|
+
function localized(pathname${ts ? ': string' : ''}, locale${ts ? ': string' : ''}) {
|
|
208
|
+
if (locale === sourceLocale) return pathname;
|
|
209
|
+
return pathname === '/' ? \`/\${locale}\` : \`/\${locale}\${pathname}\`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** hreflang alternates for search engines, as an HTTP Link header. */
|
|
213
|
+
function alternates(${req}, pathname${ts ? ': string' : ''}) {
|
|
214
|
+
const origin = request.nextUrl.origin;
|
|
215
|
+
const links = locales.map((l) => \`<\${origin}\${localized(pathname, l)}>; rel="alternate"; hreflang="\${l}"\`);
|
|
216
|
+
links.push(\`<\${origin}\${pathname}>; rel="alternate"; hreflang="x-default"\`);
|
|
217
|
+
return links.join(', ');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req}) {
|
|
221
|
+
const { pathname } = request.nextUrl;
|
|
222
|
+
const [, first = '', ...rest] = pathname.split('/');
|
|
223
|
+
const prefixed = locales.find((l) => l !== sourceLocale && l.toLowerCase() === first.toLowerCase());
|
|
224
|
+
|
|
225
|
+
if (prefixed) {
|
|
226
|
+
// /ja/docs is app/docs, in Japanese.
|
|
227
|
+
const url = request.nextUrl.clone();
|
|
228
|
+
url.pathname = \`/\${rest.join('/')}\`;
|
|
229
|
+
const headers = new Headers(request.headers);
|
|
230
|
+
headers.set('${exports.LOCALE_HEADER}', prefixed);
|
|
231
|
+
const response = NextResponse.rewrite(url, { request: { headers } });
|
|
232
|
+
response.cookies.set('NEXT_LOCALE', prefixed, { path: '/', maxAge: ONE_YEAR, sameSite: 'lax' });
|
|
233
|
+
response.headers.set('Link', alternates(request, url.pathname));
|
|
234
|
+
return response;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// An unprefixed URL is the source language, unless the visitor chose another.
|
|
238
|
+
const chosen = request.cookies.get('NEXT_LOCALE')?.value;
|
|
239
|
+
if (chosen && chosen !== sourceLocale && locales.includes(chosen)) {
|
|
240
|
+
const url = request.nextUrl.clone();
|
|
241
|
+
url.pathname = localized(pathname, chosen);
|
|
242
|
+
return NextResponse.redirect(url);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const headers = new Headers(request.headers);
|
|
246
|
+
headers.set('${exports.LOCALE_HEADER}', sourceLocale);
|
|
247
|
+
const response = NextResponse.next({ request: { headers } });
|
|
248
|
+
response.headers.set('Link', alternates(request, pathname));
|
|
249
|
+
return response;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export const config = {
|
|
253
|
+
// Pages only: not API routes, Next.js internals or files (anything with a dot).
|
|
254
|
+
matcher: ['/((?!api|trpc|_next|_vercel|.*\\\\..*).*)'],
|
|
255
|
+
};
|
|
256
|
+
`;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Give the root layout's <html> the active locale's `lang` and `dir`
|
|
260
|
+
* (#380): `const locale = useLocale()` in the default-exported layout
|
|
261
|
+
* (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
|
|
262
|
+
* can edit safely (no <html>, an expression-bodied arrow, no default export).
|
|
263
|
+
*/
|
|
264
|
+
function setHtmlLocale(content, typescript, localesImport) {
|
|
265
|
+
if (/\blocaleDirection\(/.test(content))
|
|
266
|
+
return content;
|
|
267
|
+
let ast;
|
|
268
|
+
try {
|
|
269
|
+
ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript: typescript });
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
let fn = null;
|
|
275
|
+
for (const node of ast.program.body) {
|
|
276
|
+
if (!ast_helpers_1.t.isExportDefaultDeclaration(node))
|
|
277
|
+
continue;
|
|
278
|
+
const decl = node.declaration;
|
|
279
|
+
if (ast_helpers_1.t.isFunctionDeclaration(decl) || ast_helpers_1.t.isFunctionExpression(decl) || ast_helpers_1.t.isArrowFunctionExpression(decl))
|
|
280
|
+
fn = decl;
|
|
281
|
+
else if (ast_helpers_1.t.isIdentifier(decl)) {
|
|
282
|
+
for (const other of ast.program.body) {
|
|
283
|
+
if (ast_helpers_1.t.isFunctionDeclaration(other) && other.id?.name === decl.name)
|
|
284
|
+
fn = other;
|
|
285
|
+
if (ast_helpers_1.t.isVariableDeclaration(other)) {
|
|
286
|
+
for (const d of other.declarations) {
|
|
287
|
+
if (ast_helpers_1.t.isIdentifier(d.id, { name: decl.name }) && (ast_helpers_1.t.isArrowFunctionExpression(d.init) || ast_helpers_1.t.isFunctionExpression(d.init)))
|
|
288
|
+
fn = d.init;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (!fn || !ast_helpers_1.t.isBlockStatement(fn.body) || fn.body.start == null || fn.start == null)
|
|
295
|
+
return null;
|
|
296
|
+
let html = null;
|
|
297
|
+
(0, ast_helpers_1.traverse)(ast, {
|
|
298
|
+
JSXOpeningElement(p) {
|
|
299
|
+
if (ast_helpers_1.t.isJSXIdentifier(p.node.name, { name: 'html' })) {
|
|
300
|
+
html = p.node;
|
|
301
|
+
p.stop();
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
const opening = html;
|
|
306
|
+
if (!opening || opening.name.end == null)
|
|
307
|
+
return null;
|
|
308
|
+
// A sync layout stays sync: it may call useTranslations(), which next-intl
|
|
309
|
+
// forbids in async components. useLocale() works in sync Server Components.
|
|
310
|
+
const read = fn.async
|
|
311
|
+
? { importLine: `import { getLocale } from 'next-intl/server';`, call: 'await getLocale()' }
|
|
312
|
+
: { importLine: `import { useLocale } from 'next-intl';`, call: 'useLocale()' };
|
|
313
|
+
// `useLocale` joins an existing `import { … } from 'next-intl'` (the provider's) rather than a second line.
|
|
314
|
+
const source = fn.async ? 'next-intl/server' : 'next-intl';
|
|
315
|
+
const named = fn.async ? 'getLocale' : 'useLocale';
|
|
316
|
+
const existing = ast.program.body.find((n) => ast_helpers_1.t.isImportDeclaration(n) && n.source.value === source && n.importKind !== 'type' &&
|
|
317
|
+
n.specifiers.length > 0 && n.specifiers.every((sp) => ast_helpers_1.t.isImportSpecifier(sp)));
|
|
318
|
+
const lastSpecifier = existing?.specifiers[existing.specifiers.length - 1];
|
|
319
|
+
const imports = [
|
|
320
|
+
...(lastSpecifier ? [] : [read.importLine]),
|
|
321
|
+
`import { localeDirection } from ${JSON.stringify(localesImport)};`,
|
|
322
|
+
].join('\n');
|
|
323
|
+
const splices = [
|
|
324
|
+
...(lastSpecifier?.end != null ? [{ at: lastSpecifier.end, insert: `, ${named}` }] : []),
|
|
325
|
+
insertTopLevel(ast, imports),
|
|
326
|
+
{ at: fn.body.start + 1, insert: `\n const locale = ${read.call};` },
|
|
327
|
+
];
|
|
328
|
+
// New attributes go after the existing ones: <html lang={locale} dir={…}>.
|
|
329
|
+
const lastAttr = opening.attributes[opening.attributes.length - 1];
|
|
330
|
+
const appendAt = lastAttr?.end ?? opening.name.end;
|
|
331
|
+
for (const [name, value] of [['lang', '{locale}'], ['dir', '{localeDirection(locale)}']]) {
|
|
332
|
+
const attr = opening.attributes.find((a) => ast_helpers_1.t.isJSXAttribute(a) && ast_helpers_1.t.isJSXIdentifier(a.name, { name }));
|
|
333
|
+
if (attr?.value && attr.value.start != null && attr.value.end != null) {
|
|
334
|
+
splices.push({ at: attr.value.start, remove: attr.value.end - attr.value.start, insert: value });
|
|
335
|
+
}
|
|
336
|
+
else if (!attr) {
|
|
337
|
+
splices.push({ at: appendAt, insert: ` ${name}=${value}` });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return applySplices(content, splices);
|
|
341
|
+
}
|
|
342
|
+
/** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
|
|
343
|
+
function nextMajor(packageJson) {
|
|
344
|
+
const range = packageJson?.dependencies?.next ?? packageJson?.devDependencies?.next;
|
|
345
|
+
const m = typeof range === 'string' ? /(\d+)/.exec(range) : null;
|
|
346
|
+
return m ? Number(m[1]) : null;
|
|
347
|
+
}
|
|
348
|
+
/** `routing` from .babelize/config.json: `cookie` opts out of locale URLs. */
|
|
349
|
+
async function readRouting(workspacePath) {
|
|
350
|
+
try {
|
|
351
|
+
const raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'));
|
|
352
|
+
return raw?.routing === 'cookie' ? 'cookie' : 'prefix';
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return 'prefix';
|
|
356
|
+
}
|
|
357
|
+
}
|
|
141
358
|
/** Wrap the next.config default export / module.exports with next-intl's plugin. */
|
|
142
359
|
function wrapNextConfig(content, requestConfigPath, typescript) {
|
|
143
360
|
if (content.includes('next-intl/plugin'))
|
|
@@ -298,6 +515,24 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
298
515
|
// the content's syntax always matches its extension and next.config points
|
|
299
516
|
// at a file that exists.
|
|
300
517
|
const requestDir = path.join(path.dirname(appDir), 'i18n');
|
|
518
|
+
const routing = await readRouting(workspace.path);
|
|
519
|
+
const locales = await availableLocales(workspace, options);
|
|
520
|
+
const sourceLocale = options.sourceLocale ?? 'en';
|
|
521
|
+
// 0. i18n/locales — the locale list the request config, proxy and layout share.
|
|
522
|
+
const localesFile = (await findFirst(requestDir, ['locales.ts', 'locales.js'])) ?? path.join(requestDir, `locales.${typescript ? 'ts' : 'js'}`);
|
|
523
|
+
const localesContent = await (0, file_utils_1.readFile)(localesFile).catch(() => null);
|
|
524
|
+
const ownsLocales = localesContent === null || localesContent.includes(LOCALES_MARKER);
|
|
525
|
+
if (!ownsLocales) {
|
|
526
|
+
warnings.push(`${toPosix(path.relative(root, localesFile))} already exists and was not generated by Babelize; left untouched. ` +
|
|
527
|
+
'It must export sourceLocale, locales and localeDirection(locale).');
|
|
528
|
+
}
|
|
529
|
+
else {
|
|
530
|
+
const content = buildLocalesModule({ sourceLocale, locales, typescript: /\.ts$/.test(localesFile) });
|
|
531
|
+
if (content !== localesContent) {
|
|
532
|
+
await writer.write(localesFile, content);
|
|
533
|
+
configFileCreated = true;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
301
536
|
const existingRequest = await findFirst(requestDir, ['request.ts', 'request.tsx', 'request.js', 'request.jsx', 'request.mjs']);
|
|
302
537
|
const requestFile = existingRequest ?? path.join(requestDir, `request.${typescript ? 'ts' : 'js'}`);
|
|
303
538
|
const requestIsTs = /\.tsx?$/.test(requestFile);
|
|
@@ -312,12 +547,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
312
547
|
let messagesImportPath = toPosix(path.relative(requestDir, sampleLocale));
|
|
313
548
|
if (!messagesImportPath.startsWith('.'))
|
|
314
549
|
messagesImportPath = `./${messagesImportPath}`;
|
|
315
|
-
const content = buildRequestConfig({
|
|
316
|
-
sourceLocale: options.sourceLocale ?? 'en',
|
|
317
|
-
locales: await availableLocales(workspace, options),
|
|
318
|
-
messagesImportPath,
|
|
319
|
-
typescript: requestIsTs,
|
|
320
|
-
});
|
|
550
|
+
const content = buildRequestConfig({ sourceLocale, locales, messagesImportPath, typescript: requestIsTs, routing });
|
|
321
551
|
if (content !== existingContent) {
|
|
322
552
|
await writer.write(requestFile, content);
|
|
323
553
|
configFileCreated = true;
|
|
@@ -346,14 +576,38 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
346
576
|
configFileCreated = true;
|
|
347
577
|
}
|
|
348
578
|
}
|
|
349
|
-
// 3.
|
|
579
|
+
// 3. proxy.ts (middleware.ts before Next 16) — a URL per language (#380).
|
|
580
|
+
if (routing === 'prefix') {
|
|
581
|
+
const proxyDir = path.dirname(appDir);
|
|
582
|
+
const existingProxy = await findFirst(proxyDir, PROXY_FILES);
|
|
583
|
+
const proxyContent = existingProxy ? await (0, file_utils_1.readFile)(existingProxy).catch(() => '') : null;
|
|
584
|
+
if (existingProxy && !proxyContent.includes(PROXY_MARKER)) {
|
|
585
|
+
warnings.push(`${toPosix(path.relative(root, existingProxy))} already exists, so locale URLs (/ja/…) were not set up. ` +
|
|
586
|
+
`Rewrite /<locale>/… to /… with the ${exports.LOCALE_HEADER} request header set to the locale (Babelize's generated proxy does this), ` +
|
|
587
|
+
'or set "routing": "cookie" in .babelize/config.json to keep one URL for every language.');
|
|
588
|
+
}
|
|
589
|
+
else {
|
|
590
|
+
// Our earlier file keeps its name (middleware.ts still runs on Next 16).
|
|
591
|
+
const proxyFile = existingProxy
|
|
592
|
+
?? path.join(proxyDir, `${(nextMajor(workspace.packageJson) ?? 16) >= 16 ? 'proxy' : 'middleware'}.${typescript ? 'ts' : 'js'}`);
|
|
593
|
+
const kind = path.basename(proxyFile).startsWith('proxy') ? 'proxy' : 'middleware';
|
|
594
|
+
const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile) });
|
|
595
|
+
if (content !== proxyContent) {
|
|
596
|
+
await writer.write(proxyFile, content);
|
|
597
|
+
configFileCreated = true;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
// 4. Root layout — NextIntlClientProvider so Client Components can use
|
|
602
|
+
// useTranslations(), and <html lang dir> from the active locale.
|
|
350
603
|
const layoutPath = await findFirst(appDir, LAYOUT_FILES);
|
|
351
604
|
if (!layoutPath) {
|
|
352
605
|
warnings.push('No root layout found in app/: wrap your app in <NextIntlClientProvider> from next-intl.');
|
|
353
606
|
}
|
|
354
607
|
else {
|
|
355
608
|
const content = await (0, file_utils_1.readFile)(layoutPath);
|
|
356
|
-
const
|
|
609
|
+
const layoutIsTs = /\.tsx?$/.test(layoutPath);
|
|
610
|
+
let wrapped = wrapRootLayout(content, layoutIsTs, { suspense: cacheComponents });
|
|
357
611
|
const layoutName = toPosix(path.relative(root, layoutPath));
|
|
358
612
|
if (cacheComponents && content.includes('NextIntlClientProvider') && !/<Suspense\b/.test(content)) {
|
|
359
613
|
warnings.push(`next.config enables cacheComponents, and ${layoutName} renders NextIntlClientProvider outside <Suspense>. ` +
|
|
@@ -363,7 +617,24 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
|
|
|
363
617
|
warnings.push(`Could not find {children} inside <body> in ${layoutName}: ` +
|
|
364
618
|
'wrap it in <NextIntlClientProvider> from next-intl so Client Components can translate.');
|
|
365
619
|
}
|
|
366
|
-
|
|
620
|
+
// Cache Components can't read the locale outside <Suspense>, and <html> can't be inside one.
|
|
621
|
+
if (ownsLocales && !cacheComponents) {
|
|
622
|
+
let localesImport = toPosix(path.relative(path.dirname(layoutPath), localesFile)).replace(/\.(t|j)s$/, '');
|
|
623
|
+
if (!localesImport.startsWith('.'))
|
|
624
|
+
localesImport = `./${localesImport}`;
|
|
625
|
+
const located = setHtmlLocale(wrapped ?? content, layoutIsTs, localesImport);
|
|
626
|
+
if (located === null) {
|
|
627
|
+
warnings.push(`Could not set <html lang> and dir in ${layoutName}: use \`lang={await getLocale()}\` (next-intl/server) and ` +
|
|
628
|
+
`dir={localeDirection(locale)} from ${localesImport}, or right-to-left languages render left-to-right.`);
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
wrapped = located;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
else if (cacheComponents && locales.some(rtl_languages_1.isRTL)) {
|
|
635
|
+
warnings.push(`${layoutName}: set <html lang> and dir from the locale yourself (Cache Components is on); right-to-left languages need dir="rtl".`);
|
|
636
|
+
}
|
|
637
|
+
if (wrapped !== null && wrapped !== content) {
|
|
367
638
|
await writer.write(layoutPath, wrapped);
|
|
368
639
|
entryPointModified = true;
|
|
369
640
|
}
|
|
@@ -43,6 +43,7 @@ const file_utils_1 = require("../../utils/file-utils");
|
|
|
43
43
|
const types_1 = require("../../runtime/types");
|
|
44
44
|
const StrategyFactory_1 = require("../../injection/StrategyFactory");
|
|
45
45
|
const generator_1 = require("@babel/generator");
|
|
46
|
+
const source_scope_1 = require("../../utils/source-scope");
|
|
46
47
|
/** The local name of `import X from 'i18next'` in a file, if it has one. */
|
|
47
48
|
function i18nextDefaultImport(ast) {
|
|
48
49
|
for (const node of ast.program.body) {
|
|
@@ -91,7 +92,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
|
|
|
91
92
|
const sourceFiles = [];
|
|
92
93
|
for (const sourceDir of workspace.sourceDirs) {
|
|
93
94
|
const dirPath = path.join(workspace.path, sourceDir);
|
|
94
|
-
const files = await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace));
|
|
95
|
+
const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace)));
|
|
95
96
|
sourceFiles.push(...files);
|
|
96
97
|
}
|
|
97
98
|
// Build a lookup of format strings by (relative file path, line)
|
|
@@ -225,7 +226,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
|
|
|
225
226
|
const htmlExtensions = ['.html', '.htm'];
|
|
226
227
|
for (const sourceDir of workspace.sourceDirs) {
|
|
227
228
|
const dirPath = path.join(workspace.path, sourceDir);
|
|
228
|
-
const files = await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace));
|
|
229
|
+
const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace)));
|
|
229
230
|
for (const filePath of files) {
|
|
230
231
|
const relativePath = (0, file_utils_1.getRelativePath)(workspace.path, filePath);
|
|
231
232
|
const fileStrings = stringsByFile.get(relativePath);
|
|
@@ -49,6 +49,7 @@ const file_utils_1 = require("../../utils/file-utils");
|
|
|
49
49
|
const i18n_config_path_1 = require("../../utils/i18n-config-path");
|
|
50
50
|
const i18next_icu_1 = require("../../utils/i18next-icu");
|
|
51
51
|
const string_utils_1 = require("../../utils/string-utils");
|
|
52
|
+
const source_scope_1 = require("../../utils/source-scope");
|
|
52
53
|
const ast_helpers_1 = require("../../utils/ast-helpers");
|
|
53
54
|
/**
|
|
54
55
|
* An arrow function that defines a component: assigned to a capitalized name
|
|
@@ -414,7 +415,7 @@ positions) {
|
|
|
414
415
|
const sourceFiles = [];
|
|
415
416
|
for (const sourceDir of workspace.sourceDirs) {
|
|
416
417
|
const dirPath = path.join(workspace.path, sourceDir);
|
|
417
|
-
const files = await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace));
|
|
418
|
+
const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace)));
|
|
418
419
|
sourceFiles.push(...files);
|
|
419
420
|
}
|
|
420
421
|
// react-i18next projects get Babelize's config, which exports a module-level
|
|
@@ -43,6 +43,7 @@ const types_1 = require("../../runtime/types");
|
|
|
43
43
|
const types_2 = require("@babelize/types");
|
|
44
44
|
const extraction_options_1 = require("../../utils/extraction-options");
|
|
45
45
|
const validate_1 = require("../workspace/validate");
|
|
46
|
+
const source_scope_1 = require("../../utils/source-scope");
|
|
46
47
|
/**
|
|
47
48
|
* Extraction options the project's engine runs use (sentence grouping, ICU
|
|
48
49
|
* plurals, data-literal rules), so a sync check compares like with like and
|
|
@@ -148,9 +149,11 @@ async function detectSyncIssues(projectId, workspacePath, changedFiles, commitSh
|
|
|
148
149
|
// 1. Filter changed files to only source files
|
|
149
150
|
const extractOptions = await runExtractionOptions(workspacePath, options);
|
|
150
151
|
const frameworkExcludes = types_2.FRAMEWORK_CONFIGS[extractOptions.framework]?.excludedPatterns ?? [];
|
|
152
|
+
// Files outside the project's include/exclude are never translated, so changing them can't drift.
|
|
153
|
+
const inScope = (0, source_scope_1.createScopeMatcher)(await (0, source_scope_1.readSourceScope)(workspacePath));
|
|
151
154
|
const sourceFiles = [];
|
|
152
155
|
for (const file of changedFiles) {
|
|
153
|
-
if (isSourceFile(file, frameworkExcludes)) {
|
|
156
|
+
if (isSourceFile(file, frameworkExcludes) && inScope(file)) {
|
|
154
157
|
sourceFiles.push(file);
|
|
155
158
|
}
|
|
156
159
|
else {
|
|
@@ -49,6 +49,7 @@ 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
51
|
const existing_setup_1 = require("./existing-setup");
|
|
52
|
+
const source_scope_1 = require("../../utils/source-scope");
|
|
52
53
|
const PY_IGNORE = ['**/node_modules/**', '**/.venv/**', '**/venv/**', '**/site-packages/**', '**/.git/**'];
|
|
53
54
|
/**
|
|
54
55
|
* The Django project root (directory of the shallowest manage.py), relative
|
|
@@ -252,6 +253,11 @@ async function validateWorkspace(config) {
|
|
|
252
253
|
}
|
|
253
254
|
const babelizeDir = path.join(workspacePath, '.babelize');
|
|
254
255
|
await (0, file_utils_1.ensureDir)(babelizeDir);
|
|
256
|
+
// The project's include/exclude (#378): a published library's components,
|
|
257
|
+
// its CLI or fixtures stay untouched while the app around them is localized.
|
|
258
|
+
const sourceScope = (0, source_scope_1.mergeSourceScope)(await (0, source_scope_1.readSourceScope)(workspacePath), config.sourceScope);
|
|
259
|
+
if ((0, source_scope_1.hasSourceScope)(sourceScope))
|
|
260
|
+
logger_1.engineLogger.info('Limiting the run to the configured source scope', { ...sourceScope });
|
|
255
261
|
const workspace = {
|
|
256
262
|
path: workspacePath,
|
|
257
263
|
framework,
|
|
@@ -262,6 +268,7 @@ async function validateWorkspace(config) {
|
|
|
262
268
|
publicDir,
|
|
263
269
|
...(appDir !== '.' ? { appDir } : {}),
|
|
264
270
|
...(frameworkConfig.excludedPatterns ? { excludedPatterns: frameworkConfig.excludedPatterns } : {}),
|
|
271
|
+
...((0, source_scope_1.hasSourceScope)(sourceScope) ? { sourceScope } : {}),
|
|
265
272
|
packageJson: (packageJson ?? {}),
|
|
266
273
|
formatConfig: config.formatConfig,
|
|
267
274
|
...(framework === 'django' ? { djangoRoot: djangoRoot ?? '.' } : {}),
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { ByokProvider, FormatLocaleConfig, Framework } from '@babelize/type
|
|
|
9
9
|
import type { EngineProviders, TranslationFailure } from '../providers/types';
|
|
10
10
|
import type { EngineLogger } from '../utils/logger';
|
|
11
11
|
import type { I18nLibraryId } from '../detection/i18n';
|
|
12
|
+
import type { SourceScope } from '../utils/source-scope';
|
|
12
13
|
export interface EngineConfigV2 {
|
|
13
14
|
/** Path to the workspace directory */
|
|
14
15
|
workspacePath: string;
|
|
@@ -26,6 +27,11 @@ export interface EngineConfigV2 {
|
|
|
26
27
|
dryRun: boolean;
|
|
27
28
|
/** Force translation even if locale files exist */
|
|
28
29
|
forceTranslation?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Source files this run may extract from and rewrite. Each list given
|
|
32
|
+
* replaces the same list in `.babelize/config.json` (`--include`/`--exclude`).
|
|
33
|
+
*/
|
|
34
|
+
sourceScope?: SourceScope;
|
|
29
35
|
/**
|
|
30
36
|
* Most (key, locale) pairs this run may send to the translator: the
|
|
31
37
|
* caller's credit budget. Pairs past it are left untranslated (not in the
|
|
@@ -126,6 +132,8 @@ export interface WorkspaceInfo {
|
|
|
126
132
|
appDir?: string;
|
|
127
133
|
/** Framework-specific scan exclusions (FrameworkConfig.excludedPatterns); see workspaceExcludes(). */
|
|
128
134
|
excludedPatterns?: readonly string[];
|
|
135
|
+
/** The project's `include`/`exclude` globs (config.json, or the run's override); see filterToScope(). */
|
|
136
|
+
sourceScope?: SourceScope;
|
|
129
137
|
packageJson?: Record<string, any>;
|
|
130
138
|
/** Output locale file format (e.g., 'json' for React, 'po' for Django) */
|
|
131
139
|
localeFormat: 'json' | 'po' | 'arb';
|
|
@@ -831,6 +831,35 @@ function getParentContext(path) {
|
|
|
831
831
|
siblingGroupId: Math.abs(hash).toString(36),
|
|
832
832
|
};
|
|
833
833
|
}
|
|
834
|
+
/**
|
|
835
|
+
* A readable placeholder for an interpolated value, so translators and
|
|
836
|
+
* reviewers see `{locale}` rather than `{var1}` (#379): the identifier or
|
|
837
|
+
* property, or for a call the function's subject (`getLocaleLabel(l)` →
|
|
838
|
+
* `localeLabel`, `format(price)` → `price`).
|
|
839
|
+
*/
|
|
840
|
+
function placeholderName(expr) {
|
|
841
|
+
if (t.isIdentifier(expr))
|
|
842
|
+
return expr.name;
|
|
843
|
+
if ((t.isMemberExpression(expr) || t.isOptionalMemberExpression(expr)) && t.isIdentifier(expr.property) && !expr.computed)
|
|
844
|
+
return expr.property.name;
|
|
845
|
+
if (t.isCallExpression(expr) || t.isOptionalCallExpression(expr)) {
|
|
846
|
+
const callee = expr.callee;
|
|
847
|
+
const arg = expr.arguments[0];
|
|
848
|
+
const method = (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) && t.isIdentifier(callee.property) ? callee.property.name : null;
|
|
849
|
+
const fn = t.isIdentifier(callee) ? callee.name : method;
|
|
850
|
+
const subject = fn?.replace(/^(?:get|format|render|compute)(?=[A-Z])/, '');
|
|
851
|
+
if (subject && subject !== fn)
|
|
852
|
+
return subject[0].toLowerCase() + subject.slice(1);
|
|
853
|
+
// `fmt.format(price)` names its argument; `count.toFixed(1)` or `name.trim()` its receiver.
|
|
854
|
+
if (method && method !== 'format')
|
|
855
|
+
return placeholderName(callee.object);
|
|
856
|
+
if (arg)
|
|
857
|
+
return placeholderName(arg);
|
|
858
|
+
}
|
|
859
|
+
if (t.isTSAsExpression(expr) || t.isTSNonNullExpression(expr))
|
|
860
|
+
return placeholderName(expr.expression);
|
|
861
|
+
return null;
|
|
862
|
+
}
|
|
834
863
|
/**
|
|
835
864
|
* A string-building expression as one message: `\`Hi ${user.name}\`` and
|
|
836
865
|
* `'Hi ' + name` → "Hi {name}". `variables` receives the placeholder names
|
|
@@ -844,9 +873,7 @@ function extractExpressionContent(node, variables = [], expressions = []) {
|
|
|
844
873
|
let result = '';
|
|
845
874
|
const quasis = node.quasis;
|
|
846
875
|
const exprs = node.expressions;
|
|
847
|
-
const nameOf = (expr) =>
|
|
848
|
-
: t.isMemberExpression(expr) && t.isIdentifier(expr.property) ? expr.property.name
|
|
849
|
-
: `var${variables.length}`;
|
|
876
|
+
const nameOf = (expr) => placeholderName(expr) ?? `var${variables.length}`;
|
|
850
877
|
for (let i = 0; i < quasis.length; i++) {
|
|
851
878
|
// The text as it runs (`\n` is a line break), not as it's escaped in the source.
|
|
852
879
|
result += quasis[i].value.cooked ?? quasis[i].value.raw;
|
|
@@ -872,7 +899,11 @@ function extractExpressionContent(node, variables = [], expressions = []) {
|
|
|
872
899
|
+ `{${name}, plural, one {${hash}${word[1]}${suffix.one}} other {${hash}${word[1]}${suffix.other}}}`;
|
|
873
900
|
continue;
|
|
874
901
|
}
|
|
875
|
-
|
|
902
|
+
// Two different values never share a placeholder: `${a.name} and ${b.name}` → {name}, {name2}.
|
|
903
|
+
let varName = nameOf(expr);
|
|
904
|
+
const base = varName;
|
|
905
|
+
for (let n = 2; variables.some((v, j) => v === varName && !t.isNodesEquivalent(expressions[j], expr)); n++)
|
|
906
|
+
varName = `${base}${n}`;
|
|
876
907
|
variables.push(varName);
|
|
877
908
|
expressions.push(expr);
|
|
878
909
|
result += `{${varName}}`;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which source files a run may extract from and rewrite, as globs relative to
|
|
3
|
+
* the workspace root (`src/app/**`, `src/registry`). From `.babelize/config.json`
|
|
4
|
+
* `include`/`exclude`, or `--include`/`--exclude` (#378). Files outside it are
|
|
5
|
+
* never read for strings or injected into, on top of the built-in exclusions.
|
|
6
|
+
*/
|
|
7
|
+
export interface SourceScope {
|
|
8
|
+
/** Only these paths (default: every source file). */
|
|
9
|
+
include?: string[];
|
|
10
|
+
/** Never these paths, even when included. */
|
|
11
|
+
exclude?: string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Glob lists from config or flags: non-empty strings, `./` and trailing `/`
|
|
15
|
+
* dropped. A plain path (`src/registry`) also covers everything under it.
|
|
16
|
+
*/
|
|
17
|
+
export declare function normalizeScopePatterns(value: unknown): string[] | undefined;
|
|
18
|
+
/** `include`/`exclude` from `.babelize/config.json`; missing or malformed is no scope. */
|
|
19
|
+
export declare function readSourceScope(workspacePath: string): Promise<SourceScope>;
|
|
20
|
+
/** The config's scope with each list given by the caller (flags) replacing the config's. */
|
|
21
|
+
export declare function mergeSourceScope(config: SourceScope, override?: SourceScope): SourceScope;
|
|
22
|
+
/** Whether `scope` limits anything. */
|
|
23
|
+
export declare function hasSourceScope(scope: SourceScope | undefined): boolean;
|
|
24
|
+
/** A test for workspace-relative paths (either separator). No scope: everything is in. */
|
|
25
|
+
export declare function createScopeMatcher(scope: SourceScope | undefined): (relPath: string) => boolean;
|
|
26
|
+
/** `files` (absolute) inside the workspace's scope. */
|
|
27
|
+
export declare function filterToScope(workspace: {
|
|
28
|
+
path: string;
|
|
29
|
+
sourceScope?: SourceScope;
|
|
30
|
+
}, files: string[]): string[];
|
|
@@ -0,0 +1,112 @@
|
|
|
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.normalizeScopePatterns = normalizeScopePatterns;
|
|
40
|
+
exports.readSourceScope = readSourceScope;
|
|
41
|
+
exports.mergeSourceScope = mergeSourceScope;
|
|
42
|
+
exports.hasSourceScope = hasSourceScope;
|
|
43
|
+
exports.createScopeMatcher = createScopeMatcher;
|
|
44
|
+
exports.filterToScope = filterToScope;
|
|
45
|
+
const fs_1 = require("fs");
|
|
46
|
+
const path = __importStar(require("path"));
|
|
47
|
+
const picomatch_1 = __importDefault(require("picomatch"));
|
|
48
|
+
/**
|
|
49
|
+
* Glob lists from config or flags: non-empty strings, `./` and trailing `/`
|
|
50
|
+
* dropped. A plain path (`src/registry`) also covers everything under it.
|
|
51
|
+
*/
|
|
52
|
+
function normalizeScopePatterns(value) {
|
|
53
|
+
if (!Array.isArray(value))
|
|
54
|
+
return undefined;
|
|
55
|
+
const patterns = value
|
|
56
|
+
.filter((p) => typeof p === 'string')
|
|
57
|
+
.map((p) => p.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, ''))
|
|
58
|
+
.filter((p) => p.length > 0 && p !== '.');
|
|
59
|
+
return patterns.length > 0 ? patterns : undefined;
|
|
60
|
+
}
|
|
61
|
+
function expand(patterns) {
|
|
62
|
+
return patterns.flatMap((p) => (picomatch_1.default.scan(p).isGlob ? [p] : [p, `${p}/**`]));
|
|
63
|
+
}
|
|
64
|
+
/** `include`/`exclude` from `.babelize/config.json`; missing or malformed is no scope. */
|
|
65
|
+
async function readSourceScope(workspacePath) {
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
raw = JSON.parse(await fs_1.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
if (!raw || typeof raw !== 'object')
|
|
74
|
+
return {};
|
|
75
|
+
const { include, exclude } = raw;
|
|
76
|
+
return compactScope({ include: normalizeScopePatterns(include), exclude: normalizeScopePatterns(exclude) });
|
|
77
|
+
}
|
|
78
|
+
/** The config's scope with each list given by the caller (flags) replacing the config's. */
|
|
79
|
+
function mergeSourceScope(config, override = {}) {
|
|
80
|
+
return compactScope({
|
|
81
|
+
include: normalizeScopePatterns(override.include) ?? config.include,
|
|
82
|
+
exclude: normalizeScopePatterns(override.exclude) ?? config.exclude,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
function compactScope(scope) {
|
|
86
|
+
return {
|
|
87
|
+
...(scope.include ? { include: scope.include } : {}),
|
|
88
|
+
...(scope.exclude ? { exclude: scope.exclude } : {}),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** Whether `scope` limits anything. */
|
|
92
|
+
function hasSourceScope(scope) {
|
|
93
|
+
return !!(scope?.include?.length || scope?.exclude?.length);
|
|
94
|
+
}
|
|
95
|
+
/** A test for workspace-relative paths (either separator). No scope: everything is in. */
|
|
96
|
+
function createScopeMatcher(scope) {
|
|
97
|
+
if (!hasSourceScope(scope))
|
|
98
|
+
return () => true;
|
|
99
|
+
const included = scope.include?.length ? (0, picomatch_1.default)(expand(scope.include), { dot: true }) : () => true;
|
|
100
|
+
const excluded = scope.exclude?.length ? (0, picomatch_1.default)(expand(scope.exclude), { dot: true }) : () => false;
|
|
101
|
+
return (relPath) => {
|
|
102
|
+
const rel = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
103
|
+
return included(rel) && !excluded(rel);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** `files` (absolute) inside the workspace's scope. */
|
|
107
|
+
function filterToScope(workspace, files) {
|
|
108
|
+
if (!hasSourceScope(workspace.sourceScope))
|
|
109
|
+
return files;
|
|
110
|
+
const inScope = createScopeMatcher(workspace.sourceScope);
|
|
111
|
+
return files.filter((file) => inScope(path.relative(workspace.path, file)));
|
|
112
|
+
}
|
package/dist/utils/ui-copy.d.ts
CHANGED
|
@@ -31,3 +31,17 @@ export declare function isUiCopyForName(name: string | null, text: string): bool
|
|
|
31
31
|
* returns, conditionals, …) aren't initializers and are left as they are.
|
|
32
32
|
*/
|
|
33
33
|
export declare function isUiCopyLiteral(node: t.Node, parent: t.Node | null | undefined, text: string): boolean;
|
|
34
|
+
export declare function isDirectionValue(text: string): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Every string in a string-literal union type declared in `ast`
|
|
37
|
+
* (`type Mode = "native" | "english"`, `dir?: "ltr" | "rtl"`). Code that
|
|
38
|
+
* assigns, returns or defaults to one of these is choosing an option, not
|
|
39
|
+
* showing copy; translating it breaks the type and the comparison (#379).
|
|
40
|
+
*/
|
|
41
|
+
export declare function literalUnionMembers(ast: t.Node): Set<string>;
|
|
42
|
+
/**
|
|
43
|
+
* `<LanguageSwitcher label="native" />`: one lowercase token given to a
|
|
44
|
+
* component (not a DOM element) is one of its options, like `variant` or
|
|
45
|
+
* `size`, not copy. Labels people read are capitalized or several words.
|
|
46
|
+
*/
|
|
47
|
+
export declare function isComponentOptionValue(attribute: t.JSXAttribute, element: t.JSXOpeningElement, text: string): boolean;
|
package/dist/utils/ui-copy.js
CHANGED
|
@@ -38,6 +38,9 @@ exports.isMultiWordCopy = isMultiWordCopy;
|
|
|
38
38
|
exports.looksLikeCopy = looksLikeCopy;
|
|
39
39
|
exports.isUiCopyForName = isUiCopyForName;
|
|
40
40
|
exports.isUiCopyLiteral = isUiCopyLiteral;
|
|
41
|
+
exports.isDirectionValue = isDirectionValue;
|
|
42
|
+
exports.literalUnionMembers = literalUnionMembers;
|
|
43
|
+
exports.isComponentOptionValue = isComponentOptionValue;
|
|
41
44
|
const t = __importStar(require("@babel/types"));
|
|
42
45
|
/**
|
|
43
46
|
* UI copy vs program data in object / array / variable initializers.
|
|
@@ -129,3 +132,51 @@ function isUiCopyLiteral(node, parent, text) {
|
|
|
129
132
|
return looksLikeCopy(text);
|
|
130
133
|
return true;
|
|
131
134
|
}
|
|
135
|
+
/** Text direction (`dir`, `direction`): compared and passed on, never shown (#379). */
|
|
136
|
+
const DIRECTION_VALUES = new Set(['ltr', 'rtl', 'auto']);
|
|
137
|
+
function isDirectionValue(text) {
|
|
138
|
+
return DIRECTION_VALUES.has(text.trim());
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Every string in a string-literal union type declared in `ast`
|
|
142
|
+
* (`type Mode = "native" | "english"`, `dir?: "ltr" | "rtl"`). Code that
|
|
143
|
+
* assigns, returns or defaults to one of these is choosing an option, not
|
|
144
|
+
* showing copy; translating it breaks the type and the comparison (#379).
|
|
145
|
+
*/
|
|
146
|
+
function literalUnionMembers(ast) {
|
|
147
|
+
const members = new Set();
|
|
148
|
+
const visit = (node) => {
|
|
149
|
+
if (!node || typeof node !== 'object')
|
|
150
|
+
return;
|
|
151
|
+
if (Array.isArray(node)) {
|
|
152
|
+
for (const child of node)
|
|
153
|
+
visit(child);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const n = node;
|
|
157
|
+
if (t.isTSUnionType(n)) {
|
|
158
|
+
for (const type of n.types) {
|
|
159
|
+
if (t.isTSLiteralType(type) && t.isStringLiteral(type.literal))
|
|
160
|
+
members.add(type.literal.value);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? [])
|
|
164
|
+
visit(n[key]);
|
|
165
|
+
};
|
|
166
|
+
visit(ast);
|
|
167
|
+
return members;
|
|
168
|
+
}
|
|
169
|
+
/** Props whose value is always shown, even as one lowercase word (`alt="logo"`). */
|
|
170
|
+
const SHOWN_PROP = /^(?:alt|placeholder|title|aria-.+|accessibility.+)$/;
|
|
171
|
+
/**
|
|
172
|
+
* `<LanguageSwitcher label="native" />`: one lowercase token given to a
|
|
173
|
+
* component (not a DOM element) is one of its options, like `variant` or
|
|
174
|
+
* `size`, not copy. Labels people read are capitalized or several words.
|
|
175
|
+
*/
|
|
176
|
+
function isComponentOptionValue(attribute, element, text) {
|
|
177
|
+
if (!t.isJSXIdentifier(attribute.name) || SHOWN_PROP.test(attribute.name.name))
|
|
178
|
+
return false;
|
|
179
|
+
const tag = element.name;
|
|
180
|
+
const isComponent = t.isJSXMemberExpression(tag) || (t.isJSXIdentifier(tag) && /^[A-Z]/.test(tag.name));
|
|
181
|
+
return isComponent && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(text.trim());
|
|
182
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babelize/engine",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.9",
|
|
4
4
|
"description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"babelize",
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
"gettext-parser": "^9.1.1",
|
|
42
42
|
"magic-string": "^0.30",
|
|
43
43
|
"node-html-parser": "^8.0.4",
|
|
44
|
+
"picomatch": "^2.3.2",
|
|
44
45
|
"recast": "^0.23",
|
|
45
46
|
"zod": "^4.6.6"
|
|
46
47
|
},
|
|
@@ -52,6 +53,7 @@
|
|
|
52
53
|
"@types/fs-extra": "^11.0.4",
|
|
53
54
|
"@types/jest": "^30.0.0",
|
|
54
55
|
"@types/node": "^25.0.3",
|
|
56
|
+
"@types/picomatch": "^2.3.4",
|
|
55
57
|
"ajv": "^8.17.1",
|
|
56
58
|
"eslint": "^9.39.2",
|
|
57
59
|
"intl-messageformat": "^10.7.16",
|