i18next-cli 1.74.6 → 1.74.8
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/README.md +5 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/ast-visitors.js +59 -9
- package/dist/cjs/extractor/core/extractor.js +5 -4
- package/dist/cjs/extractor/core/key-finder.js +1 -1
- package/dist/cjs/extractor/core/translation-manager.js +13 -5
- package/dist/cjs/extractor/parsers/call-expression-handler.js +53 -52
- package/dist/cjs/extractor/parsers/comment-parser.js +16 -1
- package/dist/cjs/extractor/parsers/expression-resolver.js +19 -5
- package/dist/cjs/extractor/parsers/jsx-handler.js +18 -10
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/ast-visitors.js +60 -10
- package/dist/esm/extractor/core/extractor.js +5 -4
- package/dist/esm/extractor/core/key-finder.js +1 -1
- package/dist/esm/extractor/core/translation-manager.js +13 -5
- package/dist/esm/extractor/parsers/call-expression-handler.js +53 -53
- package/dist/esm/extractor/parsers/comment-parser.js +16 -1
- package/dist/esm/extractor/parsers/expression-resolver.js +19 -6
- package/dist/esm/extractor/parsers/jsx-handler.js +19 -11
- package/package.json +2 -2
- package/types/extractor/core/ast-visitors.d.ts +3 -1
- package/types/extractor/core/ast-visitors.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/key-finder.d.ts +1 -0
- package/types/extractor/core/key-finder.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts +2 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/extractor/parsers/call-expression-handler.d.ts +25 -25
- package/types/extractor/parsers/call-expression-handler.d.ts.map +1 -1
- package/types/extractor/parsers/comment-parser.d.ts +3 -2
- package/types/extractor/parsers/comment-parser.d.ts.map +1 -1
- package/types/extractor/parsers/expression-resolver.d.ts +5 -3
- package/types/extractor/parsers/expression-resolver.d.ts.map +1 -1
- package/types/extractor/parsers/jsx-handler.d.ts.map +1 -1
package/README.md
CHANGED
|
@@ -1575,6 +1575,11 @@ Extract keys from comments for documentation or edge cases:
|
|
|
1575
1575
|
// t('user.greeting', { defaultValue: 'Hello!', ns: 'common' })
|
|
1576
1576
|
```
|
|
1577
1577
|
|
|
1578
|
+
A commented template literal cannot name its keys, so it is not extracted. Instead it keeps the
|
|
1579
|
+
existing keys it matches, even with `removeUnusedKeys`: `` // t(`QUARTER.${q}`) `` keeps `QUARTER.1`,
|
|
1580
|
+
`QUARTER.2` and so on, while code can still add new `QUARTER.*` keys. Unlike `preservePatterns`, it
|
|
1581
|
+
does not stop matching keys from being extracted.
|
|
1582
|
+
|
|
1578
1583
|
### JavaScript & TypeScript Translation Files
|
|
1579
1584
|
|
|
1580
1585
|
For projects that prefer to keep everything in a single module type, you can configure the CLI to output JavaScript or TypeScript files instead of JSON.
|
package/dist/cjs/cli.js
CHANGED
|
@@ -37,7 +37,7 @@ const program = new commander.Command();
|
|
|
37
37
|
program
|
|
38
38
|
.name('i18next-cli')
|
|
39
39
|
.description('A unified, high-performance i18next CLI.')
|
|
40
|
-
.version('1.74.
|
|
40
|
+
.version('1.74.8') // This string is replaced with the actual version at build time by rollup
|
|
41
41
|
.addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
|
|
42
42
|
// new: global config override option
|
|
43
43
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
|
|
@@ -4,6 +4,7 @@ var scopeManager = require('../parsers/scope-manager.js');
|
|
|
4
4
|
var expressionResolver = require('../parsers/expression-resolver.js');
|
|
5
5
|
var callExpressionHandler = require('../parsers/call-expression-handler.js');
|
|
6
6
|
var jsxHandler = require('../parsers/jsx-handler.js');
|
|
7
|
+
var astUtils = require('../parsers/ast-utils.js');
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Array iteration methods whose callback we can bind, mapped to the position of
|
|
@@ -20,6 +21,24 @@ const ITERATION_METHODS = {
|
|
|
20
21
|
reduce: 1,
|
|
21
22
|
reduceRight: 1,
|
|
22
23
|
};
|
|
24
|
+
// `FC<Props>` / `React.FC<Props>` / `FunctionComponent<Props>` → `Props`
|
|
25
|
+
const COMPONENT_TYPES = new Set(['FC', 'FunctionComponent', 'VFC', 'VoidFunctionComponent']);
|
|
26
|
+
function componentPropsType(type) {
|
|
27
|
+
if (type?.type !== 'TsTypeReference')
|
|
28
|
+
return undefined;
|
|
29
|
+
const name = type.typeName?.type === 'TsQualifiedName' ? type.typeName.right?.value : type.typeName?.value;
|
|
30
|
+
return COMPONENT_TYPES.has(name) ? type.typeParams?.params?.[0] : undefined;
|
|
31
|
+
}
|
|
32
|
+
// `memo(fn)` / `forwardRef(fn)` → `fn`, and which type argument types its props:
|
|
33
|
+
// `memo<Props>` → 0, `forwardRef<Ref, Props>` → 1
|
|
34
|
+
const PROPS_TYPE_ARG = { memo: 0, forwardRef: 1 };
|
|
35
|
+
function reactWrapper(node) {
|
|
36
|
+
if (node?.type !== 'CallExpression')
|
|
37
|
+
return undefined;
|
|
38
|
+
const name = node.callee?.type === 'MemberExpression' ? node.callee.property?.value : node.callee?.value;
|
|
39
|
+
const propsTypeIndex = PROPS_TYPE_ARG[name];
|
|
40
|
+
return propsTypeIndex === undefined ? undefined : { fn: astUtils.unwrapParens(node.arguments?.[0]?.expression), propsTypeIndex };
|
|
41
|
+
}
|
|
23
42
|
/**
|
|
24
43
|
* AST visitor class that traverses JavaScript/TypeScript syntax trees to extract translation keys.
|
|
25
44
|
*
|
|
@@ -50,12 +69,16 @@ class ASTVisitors {
|
|
|
50
69
|
get objectKeys() {
|
|
51
70
|
return this.callExpressionHandler.objectKeys;
|
|
52
71
|
}
|
|
72
|
+
// Key patterns of commented template literals, `// t(`QUARTER.${q}`)` → `QUARTER.*`
|
|
73
|
+
keepPatterns = [];
|
|
53
74
|
scopeManager;
|
|
54
75
|
expressionResolver;
|
|
55
76
|
callExpressionHandler;
|
|
56
77
|
jsxHandler;
|
|
57
78
|
currentFile = '';
|
|
58
79
|
currentCode = '';
|
|
80
|
+
// `const C: React.FC<Props> = (props) => …` → the function → `Props`
|
|
81
|
+
componentPropsTypes = new WeakMap();
|
|
59
82
|
/**
|
|
60
83
|
* Creates a new AST visitor instance.
|
|
61
84
|
*
|
|
@@ -261,11 +284,13 @@ class ASTVisitors {
|
|
|
261
284
|
let ident;
|
|
262
285
|
if (!p)
|
|
263
286
|
continue;
|
|
287
|
+
// The props of `const C: React.FC<Props> = (props) => …` are typed by `Props`
|
|
288
|
+
const inheritedType = p === params[0] ? this.componentPropsTypes.get(node) : undefined;
|
|
264
289
|
// Destructured object param: `function f({ size }: IProps)`.
|
|
265
290
|
// Bind each destructured local name to its interface member's values.
|
|
266
291
|
const pat = p.pat ?? p.pattern ?? p;
|
|
267
292
|
if (pat.type === 'ObjectPattern') {
|
|
268
|
-
const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation;
|
|
293
|
+
const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation ?? inheritedType;
|
|
269
294
|
const members = this.expressionResolver.resolveTypeMembers(patType);
|
|
270
295
|
for (const prop of (pat.properties ?? [])) {
|
|
271
296
|
// `{ size }` / `{ size = 'all' }` → AssignmentPatternProperty (local name is the key)
|
|
@@ -289,12 +314,25 @@ class ASTVisitors {
|
|
|
289
314
|
}
|
|
290
315
|
// `({ t }: { t: TFunction<'ns'> })` → bind `t` to that namespace
|
|
291
316
|
this.bindTFunctionParam(localName, this.getMemberTypeNode(patType, memberName), typeParamConstraints);
|
|
292
|
-
if (
|
|
317
|
+
if (members?.[memberName]) {
|
|
318
|
+
this.expressionResolver.setTemporaryVariable(localName, members[memberName]);
|
|
319
|
+
if (!paramTemporaries)
|
|
320
|
+
paramTemporaries = [];
|
|
321
|
+
paramTemporaries.push(localName);
|
|
293
322
|
continue;
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
323
|
+
}
|
|
324
|
+
// `({ Bar }: DeepObject)` → `Bar.status`; `({ items }: Props)` → `items.map(({ kind }) => …)`
|
|
325
|
+
const nested = expressionResolver.nestedMembers(members, memberName);
|
|
326
|
+
if (!nested)
|
|
327
|
+
continue;
|
|
328
|
+
this.expressionResolver.setTemporaryObjectVariable(localName, nested);
|
|
329
|
+
this.expressionResolver.setArrayElementMembers(localName, nested);
|
|
330
|
+
if (!paramObjectTemporaries)
|
|
331
|
+
paramObjectTemporaries = [];
|
|
332
|
+
paramObjectTemporaries.push(localName);
|
|
333
|
+
if (!paramArrayTemporaries)
|
|
334
|
+
paramArrayTemporaries = [];
|
|
335
|
+
paramArrayTemporaries.push(localName);
|
|
298
336
|
}
|
|
299
337
|
continue;
|
|
300
338
|
}
|
|
@@ -338,7 +376,7 @@ class ASTVisitors {
|
|
|
338
376
|
paramDefaults.push(paramKey);
|
|
339
377
|
}
|
|
340
378
|
// Try to locate TypeScript type node carried on the identifier.
|
|
341
|
-
const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation));
|
|
379
|
+
const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation) ?? inheritedType);
|
|
342
380
|
let typeAnn;
|
|
343
381
|
if (rawTypeAnn) {
|
|
344
382
|
// SWC may wrap the actual TS type in a wrapper like TsTypeAnn / TsTypeAnnotation
|
|
@@ -397,12 +435,18 @@ class ASTVisitors {
|
|
|
397
435
|
// --- VISIT LOGIC ---
|
|
398
436
|
// Handle specific node types
|
|
399
437
|
switch (node.type) {
|
|
400
|
-
case 'VariableDeclarator':
|
|
438
|
+
case 'VariableDeclarator': {
|
|
401
439
|
this.scopeManager.handleVariableDeclarator(node);
|
|
402
440
|
// Capture simple variable initializers so the expressionResolver can
|
|
403
441
|
// resolve identifiers / member expressions that reference them.
|
|
404
442
|
this.expressionResolver.captureVariableDeclarator(node);
|
|
443
|
+
// `const C: React.FC<Props> = (props) => …` / `= memo((props) => …)`
|
|
444
|
+
const propsType = componentPropsType(node.id?.typeAnnotation?.typeAnnotation);
|
|
445
|
+
const init = astUtils.unwrapParens(node.init);
|
|
446
|
+
if (propsType && init)
|
|
447
|
+
this.componentPropsTypes.set(reactWrapper(init)?.fn ?? init, propsType);
|
|
405
448
|
break;
|
|
449
|
+
}
|
|
406
450
|
case 'TSEnumDeclaration':
|
|
407
451
|
case 'TsEnumDeclaration':
|
|
408
452
|
case 'TsEnumDecl':
|
|
@@ -425,9 +469,15 @@ class ASTVisitors {
|
|
|
425
469
|
case 'FnDecl':
|
|
426
470
|
this.expressionResolver.captureFunctionDeclaration(node);
|
|
427
471
|
break;
|
|
428
|
-
case 'CallExpression':
|
|
472
|
+
case 'CallExpression': {
|
|
429
473
|
this.callExpressionHandler.handleCallExpression(node, this.scopeManager.getVarFromScope.bind(this.scopeManager));
|
|
474
|
+
// `forwardRef<Ref, Props>((props, ref) => …)` / `memo<Props>((props) => …)`
|
|
475
|
+
const wrapper = reactWrapper(node);
|
|
476
|
+
const propsType = wrapper && node.typeArguments?.params?.[wrapper.propsTypeIndex];
|
|
477
|
+
if (propsType && wrapper.fn)
|
|
478
|
+
this.componentPropsTypes.set(wrapper.fn, propsType);
|
|
430
479
|
break;
|
|
480
|
+
}
|
|
431
481
|
case 'NewExpression':
|
|
432
482
|
// Handle NewExpression similarly to CallExpression (e.g., new TranslatedError(...))
|
|
433
483
|
// NewExpression has the same structure: callee and arguments
|
|
@@ -56,9 +56,10 @@ async function runExtractor(config, options = {}) {
|
|
|
56
56
|
const spinner = wrapOra.createSpinnerLike('Running i18next key extractor...\n', { quiet: !!options.quiet, logger: options.logger });
|
|
57
57
|
try {
|
|
58
58
|
const fileErrors = [];
|
|
59
|
-
const { allKeys, objectKeys } = await keyFinder.findKeys(config, internalLogger, fileErrors);
|
|
59
|
+
const { allKeys, objectKeys, keepPatterns } = await keyFinder.findKeys(config, internalLogger, fileErrors);
|
|
60
60
|
spinner.text = `Found ${allKeys.size} unique keys. Updating translation files...`;
|
|
61
61
|
const results = await translationManager.getTranslations(allKeys, objectKeys, config, {
|
|
62
|
+
keepPatterns,
|
|
62
63
|
syncPrimaryWithDefaults: options.syncPrimaryWithDefaults,
|
|
63
64
|
syncAll: options.syncAll,
|
|
64
65
|
trustDerivedDefaults: options.trustDerivedDefaults,
|
|
@@ -304,7 +305,7 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
304
305
|
astVisitors.visit(ast);
|
|
305
306
|
// 4. THEN: Extract keys from comments with scope resolution (now scope info is available)
|
|
306
307
|
if (config.extract.extractFromComments !== false) {
|
|
307
|
-
commentParser.extractKeysFromComments(code, pluginContext, config, astVisitors.getVarFromScope.bind(astVisitors));
|
|
308
|
+
commentParser.extractKeysFromComments(code, pluginContext, config, astVisitors.getVarFromScope.bind(astVisitors), astVisitors.keepPatterns);
|
|
308
309
|
}
|
|
309
310
|
}
|
|
310
311
|
catch (error) {
|
|
@@ -428,8 +429,8 @@ async function extract(config, { syncPrimaryWithDefaults = false } = {}) {
|
|
|
428
429
|
config.extract.secondaryLanguages ||= config.locales.filter((l) => l !== config?.extract?.primaryLanguage);
|
|
429
430
|
config.extract.functions ||= ['t', '*.t'];
|
|
430
431
|
config.extract.transComponents ||= ['Trans'];
|
|
431
|
-
const { allKeys, objectKeys } = await keyFinder.findKeys(config);
|
|
432
|
-
return translationManager.getTranslations(allKeys, objectKeys, config, { syncPrimaryWithDefaults });
|
|
432
|
+
const { allKeys, objectKeys, keepPatterns } = await keyFinder.findKeys(config);
|
|
433
|
+
return translationManager.getTranslations(allKeys, objectKeys, config, { syncPrimaryWithDefaults, keepPatterns });
|
|
433
434
|
}
|
|
434
435
|
|
|
435
436
|
exports.extract = extract;
|
|
@@ -118,7 +118,7 @@ async function findKeys(config, logger$1 = new logger.ConsoleLogger(), fileError
|
|
|
118
118
|
ek.isExpandedPlural = true;
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
|
-
return { allKeys, objectKeys: astVisitors$1.objectKeys };
|
|
121
|
+
return { allKeys, objectKeys: astVisitors$1.objectKeys, keepPatterns: astVisitors$1.keepPatterns };
|
|
122
122
|
}
|
|
123
123
|
/**
|
|
124
124
|
* Processes source files using glob patterns from configuration.
|
|
@@ -166,7 +166,7 @@ function sortObjectCodeUnit(obj) {
|
|
|
166
166
|
* A helper function to build a new translation object for a single namespace.
|
|
167
167
|
* This centralizes the core logic of merging keys.
|
|
168
168
|
*/
|
|
169
|
-
function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, namespace, preservePatterns = [], objectKeys = new Set(), syncPrimaryWithDefaults = false, syncAll = false, trustDerivedDefaults = false, primaryExistingTranslations = {}, logger$1 = new logger.ConsoleLogger()) {
|
|
169
|
+
function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, namespace, preservePatterns = [], objectKeys = new Set(), syncPrimaryWithDefaults = false, syncAll = false, trustDerivedDefaults = false, primaryExistingTranslations = {}, logger$1 = new logger.ConsoleLogger(), keepPatterns = []) {
|
|
170
170
|
const { keySeparator = '.', sort = true, removeUnusedKeys = true, defaultValue: emptyDefaultValue = '', pluralSeparator = '_', contextSeparator = '_', preserveContextVariants = false, } = config.extract;
|
|
171
171
|
const primaryLanguage = config.extract.primaryLanguage || config.locales[0] || 'en';
|
|
172
172
|
const nsSep = typeof config.extract.nsSeparator === 'string' ? config.extract.nsSeparator : ':';
|
|
@@ -381,12 +381,20 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
381
381
|
}
|
|
382
382
|
return false;
|
|
383
383
|
};
|
|
384
|
+
// Patterns of commented template literals in this namespace, `// t(`QUARTER.${q}`)` (#304).
|
|
385
|
+
// Unlike preservePatterns they only keep existing keys, so code still extracts matching keys.
|
|
386
|
+
const keepRegexes = keepPatterns
|
|
387
|
+
.filter(p => !namespace || !p.ns || p.ns === '*' || p.ns === namespace)
|
|
388
|
+
.map(p => globToRegex(p.key));
|
|
384
389
|
// Helper to check if an existing key should be preserved
|
|
385
390
|
const shouldPreserveExistingKey = (key) => {
|
|
386
391
|
// 1) keys nested under a returnObjects / selector-API base key
|
|
387
392
|
if (isUnderObjectKey(key)) {
|
|
388
393
|
return true;
|
|
389
394
|
}
|
|
395
|
+
if (keepRegexes.some(re => re.test(key))) {
|
|
396
|
+
return true;
|
|
397
|
+
}
|
|
390
398
|
// 2) regex-style patterns
|
|
391
399
|
if (preservePatterns.some(re => re.test(key))) {
|
|
392
400
|
return true;
|
|
@@ -1138,7 +1146,7 @@ async function reattributeFallbackNsKeys(keysByNS, noNsToken, config, primaryLan
|
|
|
1138
1146
|
* // Results contain update status and new/existing translations for each locale.
|
|
1139
1147
|
* ```
|
|
1140
1148
|
*/
|
|
1141
|
-
async function getTranslations(keys, objectKeys, config, { syncPrimaryWithDefaults = false, syncAll = false, trustDerivedDefaults = false, logger: logger$1 = new logger.ConsoleLogger() } = {}) {
|
|
1149
|
+
async function getTranslations(keys, objectKeys, config, { syncPrimaryWithDefaults = false, syncAll = false, trustDerivedDefaults = false, logger: logger$1 = new logger.ConsoleLogger(), keepPatterns = [] } = {}) {
|
|
1142
1150
|
config.extract.primaryLanguage ||= config.locales[0] || 'en';
|
|
1143
1151
|
const primaryLanguage = config.extract.primaryLanguage || config.locales[0] || 'en';
|
|
1144
1152
|
config.extract.secondaryLanguages ||= config.locales.filter((l) => l !== primaryLanguage);
|
|
@@ -1235,13 +1243,13 @@ async function getTranslations(keys, objectKeys, config, { syncPrimaryWithDefaul
|
|
|
1235
1243
|
const nsKeys = keysByNS.get(nsKey) || [];
|
|
1236
1244
|
if (isTopLevel(nsKey)) {
|
|
1237
1245
|
// keys without namespace -> merged into top-level of the merged file
|
|
1238
|
-
const built = buildNewTranslationsForNs(nsKeys, existingMergedFile, config, locale, undefined, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryMergedFile, logger$1);
|
|
1246
|
+
const built = buildNewTranslationsForNs(nsKeys, existingMergedFile, config, locale, undefined, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryMergedFile, logger$1, keepPatterns);
|
|
1239
1247
|
Object.assign(newMergedTranslations, built);
|
|
1240
1248
|
}
|
|
1241
1249
|
else {
|
|
1242
1250
|
const existingTranslations = existingMergedFile[nsKey] || {};
|
|
1243
1251
|
const primaryExistingTranslations = primaryMergedFile[nsKey] || {};
|
|
1244
|
-
newMergedTranslations[nsKey] = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, nsKey, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryExistingTranslations, logger$1);
|
|
1252
|
+
newMergedTranslations[nsKey] = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, nsKey, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryExistingTranslations, logger$1, keepPatterns);
|
|
1245
1253
|
}
|
|
1246
1254
|
}
|
|
1247
1255
|
// Preserve ignored namespaces as-is from the existing merged file
|
|
@@ -1283,7 +1291,7 @@ async function getTranslations(keys, objectKeys, config, { syncPrimaryWithDefaul
|
|
|
1283
1291
|
const primaryExistingTranslations = locale === primaryLanguage
|
|
1284
1292
|
? existingTranslations
|
|
1285
1293
|
: (await fileUtils.loadTranslationFile(primaryOutputPath) || {});
|
|
1286
|
-
const newTranslations = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryExistingTranslations, logger$1);
|
|
1294
|
+
const newTranslations = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys, syncPrimaryWithDefaults, syncAll, trustDerivedDefaults, primaryExistingTranslations, logger$1, keepPatterns);
|
|
1287
1295
|
const oldContent = JSON.stringify(existingTranslations, null, indentation);
|
|
1288
1296
|
const newContent = JSON.stringify(newTranslations, null, indentation);
|
|
1289
1297
|
// Push one result per namespace file
|
|
@@ -11,6 +11,57 @@ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
|
11
11
|
// Used to prevent splitting keys like "Error message: not found" into namespace + key.
|
|
12
12
|
const naturalLanguageChars = /[ ,?!;]/;
|
|
13
13
|
const looksLikeNaturalLanguage = (s) => naturalLanguageChars.test(s);
|
|
14
|
+
/**
|
|
15
|
+
* Mirror i18next's runtime selector rule (v25.8.19 default, or
|
|
16
|
+
* `enableSelector: 'strict'` when `types.enableSelector === 'strict'`).
|
|
17
|
+
*
|
|
18
|
+
* **Default mode** — rewrite only when the hook was called with a multi-element
|
|
19
|
+
* namespace array and the path's first segment matches a *secondary* namespace.
|
|
20
|
+
* The primary is intentionally not rewritten (preserves #2405): its keys are
|
|
21
|
+
* exposed flat on `$`, so `$.primary.foo` means a literal sub-key.
|
|
22
|
+
*
|
|
23
|
+
* **Strict mode** — every namespace (primary included) is exposed only under
|
|
24
|
+
* its own key on `$`. So a leading segment matching *any* namespace in the
|
|
25
|
+
* scope's list — primary or secondary, single-ns or multi-ns — is rewritten.
|
|
26
|
+
* Mirrors `i18next/src/selector.js` strict branch.
|
|
27
|
+
*
|
|
28
|
+
* In strict mode we also accept a single-ns scope, falling back to
|
|
29
|
+
* `[scopeInfo.defaultNs]` when the scope didn't capture an explicit array
|
|
30
|
+
* (e.g. `useTranslation('only')`).
|
|
31
|
+
*
|
|
32
|
+
* Falls through to the input string when:
|
|
33
|
+
* - the call had no selector (string keys go through this path unchanged),
|
|
34
|
+
* - scope has no namespaces info,
|
|
35
|
+
* - first segment isn't in the scope's namespaces list, or
|
|
36
|
+
* - separators are configured off.
|
|
37
|
+
*/
|
|
38
|
+
function applySelectorNsRewrite(key, scopeInfo, config) {
|
|
39
|
+
const strict = config.types?.enableSelector === 'strict';
|
|
40
|
+
// Resolve the effective namespace list for the rule:
|
|
41
|
+
// - default mode: only the explicitly-captured `namespaces` array, length ≥ 2
|
|
42
|
+
// - strict mode: same array if present; otherwise synthesize from `defaultNs`
|
|
43
|
+
const nsCaptured = scopeInfo?.namespaces;
|
|
44
|
+
const nsList = strict
|
|
45
|
+
? (nsCaptured ?? (scopeInfo?.defaultNs ? [scopeInfo.defaultNs] : undefined))
|
|
46
|
+
: nsCaptured;
|
|
47
|
+
if (!nsList || nsList.length < (strict ? 1 : 2))
|
|
48
|
+
return key;
|
|
49
|
+
const keySeparator = config.extract.keySeparator;
|
|
50
|
+
const joiner = typeof keySeparator === 'string' ? keySeparator : '.';
|
|
51
|
+
const nsSeparator = config.extract.nsSeparator ?? ':';
|
|
52
|
+
if (keySeparator === false || !nsSeparator)
|
|
53
|
+
return key;
|
|
54
|
+
const firstSepAt = key.indexOf(joiner);
|
|
55
|
+
if (firstSepAt < 0)
|
|
56
|
+
return key;
|
|
57
|
+
const head = key.slice(0, firstSepAt);
|
|
58
|
+
// Default mode excludes the primary; strict mode includes it.
|
|
59
|
+
if (!strict && head === nsList[0])
|
|
60
|
+
return key;
|
|
61
|
+
if (!nsList.includes(head))
|
|
62
|
+
return key;
|
|
63
|
+
return `${head}${nsSeparator}${key.slice(firstSepAt + joiner.length)}`;
|
|
64
|
+
}
|
|
14
65
|
class CallExpressionHandler {
|
|
15
66
|
pluginContext;
|
|
16
67
|
config;
|
|
@@ -593,7 +644,7 @@ class CallExpressionHandler {
|
|
|
593
644
|
if (keys.length > 0) {
|
|
594
645
|
for (const k of keys) {
|
|
595
646
|
originalKeysToProcess.push(k);
|
|
596
|
-
keysToProcess.push(
|
|
647
|
+
keysToProcess.push(applySelectorNsRewrite(k, scopeInfo, this.config));
|
|
597
648
|
}
|
|
598
649
|
isSelectorAPI = true;
|
|
599
650
|
}
|
|
@@ -627,57 +678,6 @@ class CallExpressionHandler {
|
|
|
627
678
|
isSelectorAPI,
|
|
628
679
|
};
|
|
629
680
|
}
|
|
630
|
-
/**
|
|
631
|
-
* Mirror i18next's runtime selector rule (v25.8.19 default, or
|
|
632
|
-
* `enableSelector: 'strict'` when `types.enableSelector === 'strict'`).
|
|
633
|
-
*
|
|
634
|
-
* **Default mode** — rewrite only when the hook was called with a multi-element
|
|
635
|
-
* namespace array and the path's first segment matches a *secondary* namespace.
|
|
636
|
-
* The primary is intentionally not rewritten (preserves #2405): its keys are
|
|
637
|
-
* exposed flat on `$`, so `$.primary.foo` means a literal sub-key.
|
|
638
|
-
*
|
|
639
|
-
* **Strict mode** — every namespace (primary included) is exposed only under
|
|
640
|
-
* its own key on `$`. So a leading segment matching *any* namespace in the
|
|
641
|
-
* scope's list — primary or secondary, single-ns or multi-ns — is rewritten.
|
|
642
|
-
* Mirrors `i18next/src/selector.js` strict branch.
|
|
643
|
-
*
|
|
644
|
-
* In strict mode we also accept a single-ns scope, falling back to
|
|
645
|
-
* `[scopeInfo.defaultNs]` when the scope didn't capture an explicit array
|
|
646
|
-
* (e.g. `useTranslation('only')`).
|
|
647
|
-
*
|
|
648
|
-
* Falls through to the input string when:
|
|
649
|
-
* - the call had no selector (string keys go through this path unchanged),
|
|
650
|
-
* - scope has no namespaces info,
|
|
651
|
-
* - first segment isn't in the scope's namespaces list, or
|
|
652
|
-
* - separators are configured off.
|
|
653
|
-
*/
|
|
654
|
-
applySelectorNsRewrite(key, scopeInfo) {
|
|
655
|
-
const strict = this.config.types?.enableSelector === 'strict';
|
|
656
|
-
// Resolve the effective namespace list for the rule:
|
|
657
|
-
// - default mode: only the explicitly-captured `namespaces` array, length ≥ 2
|
|
658
|
-
// - strict mode: same array if present; otherwise synthesize from `defaultNs`
|
|
659
|
-
const nsCaptured = scopeInfo?.namespaces;
|
|
660
|
-
const nsList = strict
|
|
661
|
-
? (nsCaptured ?? (scopeInfo?.defaultNs ? [scopeInfo.defaultNs] : undefined))
|
|
662
|
-
: nsCaptured;
|
|
663
|
-
if (!nsList || nsList.length < (strict ? 1 : 2))
|
|
664
|
-
return key;
|
|
665
|
-
const keySeparator = this.config.extract.keySeparator;
|
|
666
|
-
const joiner = typeof keySeparator === 'string' ? keySeparator : '.';
|
|
667
|
-
const nsSeparator = this.config.extract.nsSeparator ?? ':';
|
|
668
|
-
if (keySeparator === false || !nsSeparator)
|
|
669
|
-
return key;
|
|
670
|
-
const firstSepAt = key.indexOf(joiner);
|
|
671
|
-
if (firstSepAt < 0)
|
|
672
|
-
return key;
|
|
673
|
-
const head = key.slice(0, firstSepAt);
|
|
674
|
-
// Default mode excludes the primary; strict mode includes it.
|
|
675
|
-
if (!strict && head === nsList[0])
|
|
676
|
-
return key;
|
|
677
|
-
if (!nsList.includes(head))
|
|
678
|
-
return key;
|
|
679
|
-
return `${head}${nsSeparator}${key.slice(firstSepAt + joiner.length)}`;
|
|
680
|
-
}
|
|
681
681
|
/**
|
|
682
682
|
* Extracts translation key(s) from selector API arrow function.
|
|
683
683
|
*
|
|
@@ -1051,3 +1051,4 @@ class CallExpressionHandler {
|
|
|
1051
1051
|
}
|
|
1052
1052
|
|
|
1053
1053
|
exports.CallExpressionHandler = CallExpressionHandler;
|
|
1054
|
+
exports.applySelectorNsRewrite = applySelectorNsRewrite;
|
|
@@ -13,6 +13,7 @@ const looksLikeNaturalLanguage = (s) => naturalLanguageChars.test(s);
|
|
|
13
13
|
* @param pluginContext - Context object with helper methods to add found keys
|
|
14
14
|
* @param config - Configuration object containing extraction settings
|
|
15
15
|
* @param scopeResolver - Function to resolve scope information for variables (optional)
|
|
16
|
+
* @param keepPatterns - Collects the key patterns of commented template literals (optional)
|
|
16
17
|
*
|
|
17
18
|
* @example
|
|
18
19
|
* ```typescript
|
|
@@ -26,7 +27,7 @@ const looksLikeNaturalLanguage = (s) => naturalLanguageChars.test(s);
|
|
|
26
27
|
* // Extracts: user.name and app.title with their respective settings
|
|
27
28
|
* ```
|
|
28
29
|
*/
|
|
29
|
-
function extractKeysFromComments(code, pluginContext, config, scopeResolver) {
|
|
30
|
+
function extractKeysFromComments(code, pluginContext, config, scopeResolver, keepPatterns) {
|
|
30
31
|
// Hardcode the function name to 't' to prevent parsing other functions like 'test()'.
|
|
31
32
|
const functionNameToFind = 't';
|
|
32
33
|
// Use a reliable word boundary (\b) to match 't(...)' but not 'http.get(...)'.
|
|
@@ -63,6 +64,11 @@ function extractKeysFromComments(code, pluginContext, config, scopeResolver) {
|
|
|
63
64
|
if (!key || key.trim() === '') {
|
|
64
65
|
continue; // Skip empty keys
|
|
65
66
|
}
|
|
67
|
+
// `t(`QUARTER.${q}`)` cannot name its keys: it becomes the pattern `QUARTER.*`,
|
|
68
|
+
// which keeps the existing keys it matches instead of adding a literal `${q}` (#304)
|
|
69
|
+
const isPattern = match[1] === '`' && key.includes('${');
|
|
70
|
+
if (isPattern)
|
|
71
|
+
key = key.replace(/\$\{[^}]*\}/g, '*');
|
|
66
72
|
// We'll check preservePatterns after namespace resolution below
|
|
67
73
|
let ns;
|
|
68
74
|
const remainder = text.slice(match.index + match[0].length);
|
|
@@ -122,6 +128,15 @@ function extractKeysFromComments(code, pluginContext, config, scopeResolver) {
|
|
|
122
128
|
// 4. Final fallback to configured default namespace
|
|
123
129
|
if (!ns)
|
|
124
130
|
ns = config.extract.defaultNS;
|
|
131
|
+
if (isPattern) {
|
|
132
|
+
// ponytail: a pattern without any static segment (`${a}.${b}`) would keep the whole
|
|
133
|
+
// namespace, so it is dropped
|
|
134
|
+
const keySeparator = config.extract.keySeparator ?? '.';
|
|
135
|
+
const staticPart = key.replace(/\*/g, '');
|
|
136
|
+
if (keySeparator === false ? staticPart : staticPart.split(keySeparator).some(Boolean))
|
|
137
|
+
keepPatterns?.push({ key, ns });
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
125
140
|
// 5. Handle context and count combinations based on disablePlurals setting
|
|
126
141
|
if (config.extract.disablePlurals) {
|
|
127
142
|
// When plurals are disabled, ignore count for key generation. We still
|
|
@@ -552,11 +552,12 @@ class ExpressionResolver {
|
|
|
552
552
|
map[memberName] = vals;
|
|
553
553
|
continue;
|
|
554
554
|
}
|
|
555
|
-
// `Bar: { status: '201' | '400' }` → `Bar.status
|
|
555
|
+
// `Bar: { status: '201' | '400' }` → `Bar.status`, and the element of
|
|
556
|
+
// `items: Item[]` the same way so `props.items.map(({ size }) => …)` binds
|
|
556
557
|
this.memberDepth++;
|
|
557
558
|
let nested;
|
|
558
559
|
try {
|
|
559
|
-
nested = this.resolveTypeMembers(tsType);
|
|
560
|
+
nested = this.resolveTypeMembers(tsType) ?? this.resolveArrayElementMembers(tsType);
|
|
560
561
|
}
|
|
561
562
|
finally {
|
|
562
563
|
this.memberDepth--;
|
|
@@ -626,6 +627,9 @@ class ExpressionResolver {
|
|
|
626
627
|
if (tsType.type === 'TsArrayType') {
|
|
627
628
|
return this.resolveTypeMembers(tsType.elemType);
|
|
628
629
|
}
|
|
630
|
+
if (tsType.type === 'TsTypeOperator' && tsType.op === 'readonly') {
|
|
631
|
+
return this.resolveArrayElementMembers(tsType.typeAnnotation);
|
|
632
|
+
}
|
|
629
633
|
if (tsType.type === 'TsTypeReference' && tsType.typeName?.type === 'Identifier') {
|
|
630
634
|
const name = tsType.typeName.value;
|
|
631
635
|
if (name !== 'Array' && name !== 'ReadonlyArray')
|
|
@@ -673,8 +677,8 @@ class ExpressionResolver {
|
|
|
673
677
|
return Object.keys(members).length > 0 ? members : undefined;
|
|
674
678
|
}
|
|
675
679
|
/**
|
|
676
|
-
* The values an iterated array holds: a known constant (`QUARTERS.map(…)`)
|
|
677
|
-
* inline literal (`([1, 2, 3, 4] as const).map(…)`).
|
|
680
|
+
* The values an iterated array holds: a known constant (`QUARTERS.map(…)`), an
|
|
681
|
+
* inline literal (`([1, 2, 3, 4] as const).map(…)`) or a typed member (`props.colors`).
|
|
678
682
|
*/
|
|
679
683
|
arrayValuesOf(expr) {
|
|
680
684
|
expr = unwrapExpr(expr);
|
|
@@ -682,11 +686,17 @@ class ExpressionResolver {
|
|
|
682
686
|
return this.getVariableValues(expr.value);
|
|
683
687
|
if (expr?.type === 'ArrayExpression')
|
|
684
688
|
return this.arrayLiteralValues(expr);
|
|
689
|
+
// `props.colors` where `colors: Color[]`
|
|
690
|
+
if (expr?.type === 'MemberExpression') {
|
|
691
|
+
const vals = this.resolvePossibleStringValuesFromExpression(expr);
|
|
692
|
+
return vals.length > 0 ? vals : undefined;
|
|
693
|
+
}
|
|
685
694
|
return undefined;
|
|
686
695
|
}
|
|
687
696
|
/**
|
|
688
697
|
* The element member map of an iterated array of objects: a typed or constant
|
|
689
|
-
* identifier (`items: IProps[]`)
|
|
698
|
+
* identifier (`items: IProps[]`), an inline literal (`[{ unit: 'day' }]`) or a
|
|
699
|
+
* typed member (`props.items`).
|
|
690
700
|
*/
|
|
691
701
|
arrayMembersOf(expr) {
|
|
692
702
|
expr = unwrapExpr(expr);
|
|
@@ -694,6 +704,9 @@ class ExpressionResolver {
|
|
|
694
704
|
return this.arrayElementMembers.get(expr.value);
|
|
695
705
|
if (expr?.type === 'ArrayExpression')
|
|
696
706
|
return this.arrayLiteralMembers(expr);
|
|
707
|
+
// `props.items` where `items: Item[]`
|
|
708
|
+
if (expr?.type === 'MemberExpression')
|
|
709
|
+
return this.objectMembersOf(expr);
|
|
697
710
|
return undefined;
|
|
698
711
|
}
|
|
699
712
|
/**
|
|
@@ -1390,3 +1403,4 @@ class ExpressionResolver {
|
|
|
1390
1403
|
}
|
|
1391
1404
|
|
|
1392
1405
|
exports.ExpressionResolver = ExpressionResolver;
|
|
1406
|
+
exports.nestedMembers = nestedMembers;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
var pluralRules = require('../../utils/plural-rules.js');
|
|
4
4
|
var jsxParser = require('./jsx-parser.js');
|
|
5
5
|
var astUtils = require('./ast-utils.js');
|
|
6
|
+
var callExpressionHandler = require('./call-expression-handler.js');
|
|
6
7
|
|
|
7
8
|
// Checks if a string looks like natural language (contains spaces, punctuation, etc.)
|
|
8
9
|
const naturalLanguageChars = /[ ,?!;]/;
|
|
@@ -169,7 +170,22 @@ class JSXHandler {
|
|
|
169
170
|
// If ns is not explicitly set on the component, try to find it from the key
|
|
170
171
|
// or the `t` prop
|
|
171
172
|
if (!extractedAttributes.ns) {
|
|
173
|
+
const tProp = node.opening.attributes?.find(attr => attr.type === 'JSXAttribute' &&
|
|
174
|
+
attr.name.type === 'Identifier' &&
|
|
175
|
+
attr.name.value === 't');
|
|
176
|
+
// Check if the prop value is an identifier (e.g., t={t})
|
|
177
|
+
const scopeInfo = tProp?.type === 'JSXAttribute' &&
|
|
178
|
+
tProp.value?.type === 'JSXExpressionContainer' &&
|
|
179
|
+
tProp.value.expression.type === 'Identifier'
|
|
180
|
+
? getScopeInfo(tProp.value.expression.value)
|
|
181
|
+
: undefined;
|
|
182
|
+
// Trans leaves a selector key to the `t` prop, which routes it into the
|
|
183
|
+
// hook's other namespaces like t() does (react-i18next#1933)
|
|
184
|
+
const isSelector = !!extractedAttributes.keyExpression &&
|
|
185
|
+
astUtils.unwrapParens(extractedAttributes.keyExpression).type === 'ArrowFunctionExpression';
|
|
172
186
|
extractedKeys = keysToProcess.map(key => {
|
|
187
|
+
if (isSelector)
|
|
188
|
+
key = callExpressionHandler.applySelectorNsRewrite(key, scopeInfo, this.config);
|
|
173
189
|
const nsSeparator = this.config.extract.nsSeparator ?? ':';
|
|
174
190
|
let ns;
|
|
175
191
|
// If the key contains a namespace separator, it takes precedence
|
|
@@ -191,16 +207,8 @@ class JSXHandler {
|
|
|
191
207
|
locations
|
|
192
208
|
};
|
|
193
209
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
attr.name.value === 't');
|
|
197
|
-
// Check if the prop value is an identifier (e.g., t={t})
|
|
198
|
-
if (tProp?.type === 'JSXAttribute' &&
|
|
199
|
-
tProp.value?.type === 'JSXExpressionContainer' &&
|
|
200
|
-
tProp.value.expression.type === 'Identifier') {
|
|
201
|
-
const tIdentifier = tProp.value.expression.value;
|
|
202
|
-
const scopeInfo = getScopeInfo(tIdentifier);
|
|
203
|
-
if (scopeInfo?.defaultNs) {
|
|
210
|
+
if (scopeInfo) {
|
|
211
|
+
if (scopeInfo.defaultNs) {
|
|
204
212
|
// One copy per namespace when the hook's ns was a conditional (#299)
|
|
205
213
|
const scopeNamespaces = [scopeInfo.defaultNs, ...(scopeInfo.altNs ?? [])];
|
|
206
214
|
extractedKeys = extractedKeys.flatMap(key => key.ns ? [key] : scopeNamespaces.map(ns => ({ ...key, ns })));
|
package/dist/esm/cli.js
CHANGED
|
@@ -31,7 +31,7 @@ const program = new Command();
|
|
|
31
31
|
program
|
|
32
32
|
.name('i18next-cli')
|
|
33
33
|
.description('A unified, high-performance i18next CLI.')
|
|
34
|
-
.version('1.74.
|
|
34
|
+
.version('1.74.8') // This string is replaced with the actual version at build time by rollup
|
|
35
35
|
.addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
|
|
36
36
|
// new: global config override option
|
|
37
37
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
|