i18next-cli 1.74.5 → 1.74.7
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/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/ast-visitors.js +66 -26
- package/dist/cjs/extractor/parsers/call-expression-handler.js +53 -52
- package/dist/cjs/extractor/parsers/expression-resolver.js +153 -44
- 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 +67 -27
- package/dist/esm/extractor/parsers/call-expression-handler.js +53 -53
- package/dist/esm/extractor/parsers/expression-resolver.js +153 -45
- package/dist/esm/extractor/parsers/jsx-handler.js +19 -11
- package/package.json +2 -2
- package/types/extractor/core/ast-visitors.d.ts +1 -0
- package/types/extractor/core/ast-visitors.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/expression-resolver.d.ts +15 -1
- package/types/extractor/parsers/expression-resolver.d.ts.map +1 -1
- package/types/extractor/parsers/jsx-handler.d.ts.map +1 -1
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.7') // 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
|
*
|
|
@@ -56,6 +75,8 @@ class ASTVisitors {
|
|
|
56
75
|
jsxHandler;
|
|
57
76
|
currentFile = '';
|
|
58
77
|
currentCode = '';
|
|
78
|
+
// `const C: React.FC<Props> = (props) => …` → the function → `Props`
|
|
79
|
+
componentPropsTypes = new WeakMap();
|
|
59
80
|
/**
|
|
60
81
|
* Creates a new AST visitor instance.
|
|
61
82
|
*
|
|
@@ -261,11 +282,13 @@ class ASTVisitors {
|
|
|
261
282
|
let ident;
|
|
262
283
|
if (!p)
|
|
263
284
|
continue;
|
|
285
|
+
// The props of `const C: React.FC<Props> = (props) => …` are typed by `Props`
|
|
286
|
+
const inheritedType = p === params[0] ? this.componentPropsTypes.get(node) : undefined;
|
|
264
287
|
// Destructured object param: `function f({ size }: IProps)`.
|
|
265
288
|
// Bind each destructured local name to its interface member's values.
|
|
266
289
|
const pat = p.pat ?? p.pattern ?? p;
|
|
267
290
|
if (pat.type === 'ObjectPattern') {
|
|
268
|
-
const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation;
|
|
291
|
+
const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation ?? inheritedType;
|
|
269
292
|
const members = this.expressionResolver.resolveTypeMembers(patType);
|
|
270
293
|
for (const prop of (pat.properties ?? [])) {
|
|
271
294
|
// `{ size }` / `{ size = 'all' }` → AssignmentPatternProperty (local name is the key)
|
|
@@ -289,12 +312,25 @@ class ASTVisitors {
|
|
|
289
312
|
}
|
|
290
313
|
// `({ t }: { t: TFunction<'ns'> })` → bind `t` to that namespace
|
|
291
314
|
this.bindTFunctionParam(localName, this.getMemberTypeNode(patType, memberName), typeParamConstraints);
|
|
292
|
-
if (
|
|
315
|
+
if (members?.[memberName]) {
|
|
316
|
+
this.expressionResolver.setTemporaryVariable(localName, members[memberName]);
|
|
317
|
+
if (!paramTemporaries)
|
|
318
|
+
paramTemporaries = [];
|
|
319
|
+
paramTemporaries.push(localName);
|
|
293
320
|
continue;
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
321
|
+
}
|
|
322
|
+
// `({ Bar }: DeepObject)` → `Bar.status`; `({ items }: Props)` → `items.map(({ kind }) => …)`
|
|
323
|
+
const nested = expressionResolver.nestedMembers(members, memberName);
|
|
324
|
+
if (!nested)
|
|
325
|
+
continue;
|
|
326
|
+
this.expressionResolver.setTemporaryObjectVariable(localName, nested);
|
|
327
|
+
this.expressionResolver.setArrayElementMembers(localName, nested);
|
|
328
|
+
if (!paramObjectTemporaries)
|
|
329
|
+
paramObjectTemporaries = [];
|
|
330
|
+
paramObjectTemporaries.push(localName);
|
|
331
|
+
if (!paramArrayTemporaries)
|
|
332
|
+
paramArrayTemporaries = [];
|
|
333
|
+
paramArrayTemporaries.push(localName);
|
|
298
334
|
}
|
|
299
335
|
continue;
|
|
300
336
|
}
|
|
@@ -338,7 +374,7 @@ class ASTVisitors {
|
|
|
338
374
|
paramDefaults.push(paramKey);
|
|
339
375
|
}
|
|
340
376
|
// Try to locate TypeScript type node carried on the identifier.
|
|
341
|
-
const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation));
|
|
377
|
+
const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation) ?? inheritedType);
|
|
342
378
|
let typeAnn;
|
|
343
379
|
if (rawTypeAnn) {
|
|
344
380
|
// SWC may wrap the actual TS type in a wrapper like TsTypeAnn / TsTypeAnnotation
|
|
@@ -397,12 +433,18 @@ class ASTVisitors {
|
|
|
397
433
|
// --- VISIT LOGIC ---
|
|
398
434
|
// Handle specific node types
|
|
399
435
|
switch (node.type) {
|
|
400
|
-
case 'VariableDeclarator':
|
|
436
|
+
case 'VariableDeclarator': {
|
|
401
437
|
this.scopeManager.handleVariableDeclarator(node);
|
|
402
438
|
// Capture simple variable initializers so the expressionResolver can
|
|
403
439
|
// resolve identifiers / member expressions that reference them.
|
|
404
440
|
this.expressionResolver.captureVariableDeclarator(node);
|
|
441
|
+
// `const C: React.FC<Props> = (props) => …` / `= memo((props) => …)`
|
|
442
|
+
const propsType = componentPropsType(node.id?.typeAnnotation?.typeAnnotation);
|
|
443
|
+
const init = astUtils.unwrapParens(node.init);
|
|
444
|
+
if (propsType && init)
|
|
445
|
+
this.componentPropsTypes.set(reactWrapper(init)?.fn ?? init, propsType);
|
|
405
446
|
break;
|
|
447
|
+
}
|
|
406
448
|
case 'TSEnumDeclaration':
|
|
407
449
|
case 'TsEnumDeclaration':
|
|
408
450
|
case 'TsEnumDecl':
|
|
@@ -425,9 +467,15 @@ class ASTVisitors {
|
|
|
425
467
|
case 'FnDecl':
|
|
426
468
|
this.expressionResolver.captureFunctionDeclaration(node);
|
|
427
469
|
break;
|
|
428
|
-
case 'CallExpression':
|
|
470
|
+
case 'CallExpression': {
|
|
429
471
|
this.callExpressionHandler.handleCallExpression(node, this.scopeManager.getVarFromScope.bind(this.scopeManager));
|
|
472
|
+
// `forwardRef<Ref, Props>((props, ref) => …)` / `memo<Props>((props) => …)`
|
|
473
|
+
const wrapper = reactWrapper(node);
|
|
474
|
+
const propsType = wrapper && node.typeArguments?.params?.[wrapper.propsTypeIndex];
|
|
475
|
+
if (propsType && wrapper.fn)
|
|
476
|
+
this.componentPropsTypes.set(wrapper.fn, propsType);
|
|
430
477
|
break;
|
|
478
|
+
}
|
|
431
479
|
case 'NewExpression':
|
|
432
480
|
// Handle NewExpression similarly to CallExpression (e.g., new TranslatedError(...))
|
|
433
481
|
// NewExpression has the same structure: callee and arguments
|
|
@@ -809,15 +857,11 @@ class ASTVisitors {
|
|
|
809
857
|
const elementParamIndex = ITERATION_METHODS[prop.value];
|
|
810
858
|
if (elementParamIndex === undefined)
|
|
811
859
|
return undefined;
|
|
812
|
-
// The object must be an identifier whose value is a known string array
|
|
813
860
|
const obj = callee.object;
|
|
814
|
-
// ── Case 1: KNOWN_ARRAY.map(x => ...)
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
return this.extractCallbackParam(node, values, elementParamIndex);
|
|
819
|
-
}
|
|
820
|
-
}
|
|
861
|
+
// ── Case 1: KNOWN_ARRAY.map(x => ...) / ([1, 2] as const).map(x => ...)
|
|
862
|
+
const values = this.expressionResolver.arrayValuesOf(obj);
|
|
863
|
+
if (values?.length)
|
|
864
|
+
return this.extractCallbackParam(node, values, elementParamIndex);
|
|
821
865
|
// ── Case 2: Object.keys(MAP).map(k => ...) ────────────────────────────
|
|
822
866
|
// Object.values(MAP).map(v => ...)
|
|
823
867
|
// callee.object is a CallExpression: Object.keys(...) / Object.values(...)
|
|
@@ -859,20 +903,18 @@ class ASTVisitors {
|
|
|
859
903
|
*/
|
|
860
904
|
tryBindForOfLoop(node) {
|
|
861
905
|
try {
|
|
862
|
-
|
|
863
|
-
return undefined;
|
|
864
|
-
const source = node.right.value;
|
|
906
|
+
const source = node.right;
|
|
865
907
|
const left = node.left;
|
|
866
908
|
const pat = left?.type === 'VariableDeclaration' ? left.declarations?.[0]?.id : left;
|
|
867
909
|
// `for (const unit of ['day', 'hour'] as const)`
|
|
868
910
|
if (pat?.type === 'Identifier') {
|
|
869
|
-
const values = this.expressionResolver.
|
|
911
|
+
const values = this.expressionResolver.arrayValuesOf(source);
|
|
870
912
|
if (values?.length) {
|
|
871
913
|
this.expressionResolver.setTemporaryVariable(pat.value, values);
|
|
872
914
|
return () => this.expressionResolver.deleteTemporaryVariable(pat.value);
|
|
873
915
|
}
|
|
874
916
|
// `for (const item of items)` so `item.unit` resolves
|
|
875
|
-
const members = this.expressionResolver.
|
|
917
|
+
const members = this.expressionResolver.arrayMembersOf(source);
|
|
876
918
|
if (members) {
|
|
877
919
|
this.expressionResolver.setTemporaryObjectVariable(pat.value, members);
|
|
878
920
|
return () => this.expressionResolver.deleteTemporaryObjectVariable(pat.value);
|
|
@@ -881,7 +923,7 @@ class ASTVisitors {
|
|
|
881
923
|
}
|
|
882
924
|
// `for (const { unit } of [{ unit: 'day' }, …] as const)`
|
|
883
925
|
if (pat?.type === 'ObjectPattern') {
|
|
884
|
-
const members = this.expressionResolver.
|
|
926
|
+
const members = this.expressionResolver.arrayMembersOf(source);
|
|
885
927
|
if (!members)
|
|
886
928
|
return undefined;
|
|
887
929
|
const bound = [];
|
|
@@ -927,9 +969,7 @@ class ASTVisitors {
|
|
|
927
969
|
const elementParamIndex = ITERATION_METHODS[prop.value];
|
|
928
970
|
if (elementParamIndex === undefined)
|
|
929
971
|
return undefined;
|
|
930
|
-
|
|
931
|
-
return undefined;
|
|
932
|
-
const members = this.expressionResolver.getArrayElementMembers(callee.object.value);
|
|
972
|
+
const members = this.expressionResolver.arrayMembersOf(callee.object);
|
|
933
973
|
if (!members)
|
|
934
974
|
return undefined;
|
|
935
975
|
const callbackArg = node.arguments?.[0]?.expression;
|
|
@@ -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;
|
|
@@ -14,6 +14,41 @@ const covers = (next, prev) => {
|
|
|
14
14
|
}
|
|
15
15
|
return next === prev;
|
|
16
16
|
};
|
|
17
|
+
// `(x)`, `x as const`, `x as T`, `x satisfies T` -> `x`
|
|
18
|
+
const unwrapExpr = (expr) => {
|
|
19
|
+
while (['ParenthesisExpression', 'TsConstAssertion', 'TsAsExpression', 'TsSatisfiesExpression'].includes(expr?.type))
|
|
20
|
+
expr = expr.expression;
|
|
21
|
+
return expr;
|
|
22
|
+
};
|
|
23
|
+
// Nested object members are flattened to dotted paths (`{ 'Foo.Bar.status': [...] }`).
|
|
24
|
+
// ponytail: capped so recursive types (`interface Node { child: Node }`) stay small;
|
|
25
|
+
// raise it if real code reads deeper chains in a key.
|
|
26
|
+
const MAX_MEMBER_DEPTH = 5;
|
|
27
|
+
// The members nested under `name`: { 'Bar.status': v } -> { status: v }. Member maps
|
|
28
|
+
// are never changed once built, so each is split by its first segment only once:
|
|
29
|
+
// resolving every `components['schemas'][X]` of an OpenAPI schema stays linear.
|
|
30
|
+
const nestedIndex = new WeakMap();
|
|
31
|
+
const nestedMembers = (members, name) => {
|
|
32
|
+
if (!members)
|
|
33
|
+
return undefined;
|
|
34
|
+
let index = nestedIndex.get(members);
|
|
35
|
+
if (!index) {
|
|
36
|
+
index = new Map();
|
|
37
|
+
for (const [path, vals] of Object.entries(members)) {
|
|
38
|
+
const dot = path.indexOf('.');
|
|
39
|
+
if (dot < 0)
|
|
40
|
+
continue;
|
|
41
|
+
const head = path.slice(0, dot);
|
|
42
|
+
if (!index.has(head))
|
|
43
|
+
index.set(head, {});
|
|
44
|
+
index.get(head)[path.slice(dot + 1)] = vals;
|
|
45
|
+
}
|
|
46
|
+
nestedIndex.set(members, index);
|
|
47
|
+
}
|
|
48
|
+
return index.get(name);
|
|
49
|
+
};
|
|
50
|
+
// `T['a']` -> 'a'
|
|
51
|
+
const indexedKey = (type) => type?.indexType?.type === 'TsLiteralType' && type.indexType.literal?.type === 'StringLiteral' ? type.indexType.literal.value : undefined;
|
|
17
52
|
// Whether replacing `prev` by `next` only adds to it.
|
|
18
53
|
const grows = (next, prev) => prev === undefined || (covers(next, prev) && !covers(prev, next));
|
|
19
54
|
// The parts of return expressions that still resolve without the file's local
|
|
@@ -96,6 +131,7 @@ class ExpressionResolver {
|
|
|
96
131
|
replays = [];
|
|
97
132
|
replaying = false;
|
|
98
133
|
grew = false;
|
|
134
|
+
memberDepth = 0;
|
|
99
135
|
constructor(hooks) {
|
|
100
136
|
this.hooks = hooks;
|
|
101
137
|
}
|
|
@@ -252,12 +288,7 @@ class ExpressionResolver {
|
|
|
252
288
|
// Unwrap TS type assertion wrappers before inspecting the shape of the initializer.
|
|
253
289
|
// `{ ... } as const` → TsConstAssertion; `x as Type` → TsAsExpression; etc.
|
|
254
290
|
// We need the raw expression to detect ObjectExpression and ArrowFunctionExpression.
|
|
255
|
-
|
|
256
|
-
while (unwrappedInit?.type === 'TsConstAssertion' ||
|
|
257
|
-
unwrappedInit?.type === 'TsAsExpression' ||
|
|
258
|
-
unwrappedInit?.type === 'TsSatisfiesExpression') {
|
|
259
|
-
unwrappedInit = unwrappedInit.expression;
|
|
260
|
-
}
|
|
291
|
+
const unwrappedInit = unwrapExpr(init);
|
|
261
292
|
// ObjectExpression -> map of string props
|
|
262
293
|
if (unwrappedInit.type === 'ObjectExpression' && Array.isArray(unwrappedInit.properties)) {
|
|
263
294
|
const map = {};
|
|
@@ -284,15 +315,8 @@ class ExpressionResolver {
|
|
|
284
315
|
// ArrayExpression -> list of string values
|
|
285
316
|
// Handles `const OPTS = ['a', 'b', 'c'] as const`
|
|
286
317
|
if (unwrappedInit.type === 'ArrayExpression' && Array.isArray(unwrappedInit.elements)) {
|
|
287
|
-
const vals =
|
|
288
|
-
|
|
289
|
-
if (!elem || !elem.expression)
|
|
290
|
-
continue;
|
|
291
|
-
const resolved = this.resolvePossibleStringValuesFromExpression(elem.expression);
|
|
292
|
-
if (resolved.length === 1)
|
|
293
|
-
vals.push(resolved[0]);
|
|
294
|
-
}
|
|
295
|
-
if (vals.length > 0) {
|
|
318
|
+
const vals = this.arrayLiteralValues(unwrappedInit);
|
|
319
|
+
if (vals) {
|
|
296
320
|
this.variableTable.set(name, vals);
|
|
297
321
|
// Also share so importing files can see this array
|
|
298
322
|
this.sharedVariableTable.set(name, vals);
|
|
@@ -301,30 +325,8 @@ class ExpressionResolver {
|
|
|
301
325
|
// Array of object literals — `const UNITS = [{ unit: 'day' }, …] as const`.
|
|
302
326
|
// Collect each property's possible values so `UNITS.map(({ unit }) => …)`
|
|
303
327
|
// and `for (const { unit } of UNITS)` can bind the destructured names.
|
|
304
|
-
const members =
|
|
305
|
-
|
|
306
|
-
let objExpr = elem?.expression;
|
|
307
|
-
while (objExpr?.type === 'TsConstAssertion' ||
|
|
308
|
-
objExpr?.type === 'TsAsExpression' ||
|
|
309
|
-
objExpr?.type === 'TsSatisfiesExpression')
|
|
310
|
-
objExpr = objExpr.expression;
|
|
311
|
-
if (objExpr?.type !== 'ObjectExpression')
|
|
312
|
-
continue;
|
|
313
|
-
for (const p of (objExpr.properties ?? [])) {
|
|
314
|
-
if (p?.type !== 'KeyValueProperty')
|
|
315
|
-
continue;
|
|
316
|
-
const keyName = p.key?.type === 'Identifier' || p.key?.type === 'StringLiteral' ? p.key.value : undefined;
|
|
317
|
-
if (!keyName)
|
|
318
|
-
continue;
|
|
319
|
-
const resolved = this.resolvePossibleStringValuesFromExpression(p.value);
|
|
320
|
-
if (resolved.length !== 1)
|
|
321
|
-
continue;
|
|
322
|
-
const list = members[keyName] ??= [];
|
|
323
|
-
if (!list.includes(resolved[0]))
|
|
324
|
-
list.push(resolved[0]);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
if (Object.keys(members).length > 0) {
|
|
328
|
+
const members = this.arrayLiteralMembers(unwrappedInit);
|
|
329
|
+
if (members) {
|
|
328
330
|
this.arrayElementMembers.set(name, members);
|
|
329
331
|
return;
|
|
330
332
|
}
|
|
@@ -513,10 +515,18 @@ class ExpressionResolver {
|
|
|
513
515
|
*/
|
|
514
516
|
objectMembersOf(expr) {
|
|
515
517
|
expr = astUtils.unwrapParens(expr);
|
|
518
|
+
if (expr?.type === 'OptionalChainingExpression')
|
|
519
|
+
return this.objectMembersOf(expr.base);
|
|
516
520
|
if (expr?.type === 'Identifier')
|
|
517
521
|
return this.temporaryObjectVariables.get(expr.value) ?? this.objectVariables.get(expr.value);
|
|
518
522
|
if (expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier')
|
|
519
523
|
return this.sharedFunctionReturnMembers.get(expr.callee.value);
|
|
524
|
+
// `deepObject.Foo.Bar` → the members nested under `Foo.Bar`
|
|
525
|
+
if (expr?.type === 'MemberExpression') {
|
|
526
|
+
const prop = expr.property;
|
|
527
|
+
const name = prop?.type === 'Identifier' ? prop.value : prop?.type === 'Computed' && prop.expression?.type === 'StringLiteral' ? prop.expression.value : undefined;
|
|
528
|
+
return name === undefined ? undefined : nestedMembers(this.objectMembersOf(expr.object), name);
|
|
529
|
+
}
|
|
520
530
|
return undefined;
|
|
521
531
|
}
|
|
522
532
|
/**
|
|
@@ -525,7 +535,7 @@ class ExpressionResolver {
|
|
|
525
535
|
* resolves to a finite string set are kept; returns undefined when none do.
|
|
526
536
|
*/
|
|
527
537
|
collectObjectTypeMembers(members) {
|
|
528
|
-
if (!Array.isArray(members))
|
|
538
|
+
if (!Array.isArray(members) || this.memberDepth >= MAX_MEMBER_DEPTH)
|
|
529
539
|
return undefined;
|
|
530
540
|
const map = {};
|
|
531
541
|
for (const m of members) {
|
|
@@ -538,8 +548,24 @@ class ExpressionResolver {
|
|
|
538
548
|
if (!tsType)
|
|
539
549
|
continue;
|
|
540
550
|
const vals = this.resolvePossibleStringValuesFromType(tsType);
|
|
541
|
-
if (vals.length > 0)
|
|
551
|
+
if (vals.length > 0) {
|
|
542
552
|
map[memberName] = vals;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
// `Bar: { status: '201' | '400' }` → `Bar.status`, and the element of
|
|
556
|
+
// `items: Item[]` the same way so `props.items.map(({ size }) => …)` binds
|
|
557
|
+
this.memberDepth++;
|
|
558
|
+
let nested;
|
|
559
|
+
try {
|
|
560
|
+
nested = this.resolveTypeMembers(tsType) ?? this.resolveArrayElementMembers(tsType);
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
this.memberDepth--;
|
|
564
|
+
}
|
|
565
|
+
for (const [path, v] of Object.entries(nested ?? {})) {
|
|
566
|
+
if (path.split('.').length < MAX_MEMBER_DEPTH)
|
|
567
|
+
map[`${memberName}.${path}`] = v;
|
|
568
|
+
}
|
|
543
569
|
}
|
|
544
570
|
return Object.keys(map).length > 0 ? map : undefined;
|
|
545
571
|
}
|
|
@@ -556,6 +582,11 @@ class ExpressionResolver {
|
|
|
556
582
|
return undefined;
|
|
557
583
|
if (tsType.type === 'TsParenthesizedType')
|
|
558
584
|
return this.resolveTypeMembers(tsType.typeAnnotation);
|
|
585
|
+
// `components['schemas']['Pet']` → the members nested under `schemas.Pet`
|
|
586
|
+
if (tsType.type === 'TsIndexedAccessType') {
|
|
587
|
+
const key = indexedKey(tsType);
|
|
588
|
+
return key === undefined ? undefined : nestedMembers(this.resolveTypeMembers(tsType.objectType), key);
|
|
589
|
+
}
|
|
559
590
|
if (tsType.type === 'TsTypeLiteral') {
|
|
560
591
|
return this.collectObjectTypeMembers(tsType.members);
|
|
561
592
|
}
|
|
@@ -596,6 +627,9 @@ class ExpressionResolver {
|
|
|
596
627
|
if (tsType.type === 'TsArrayType') {
|
|
597
628
|
return this.resolveTypeMembers(tsType.elemType);
|
|
598
629
|
}
|
|
630
|
+
if (tsType.type === 'TsTypeOperator' && tsType.op === 'readonly') {
|
|
631
|
+
return this.resolveArrayElementMembers(tsType.typeAnnotation);
|
|
632
|
+
}
|
|
599
633
|
if (tsType.type === 'TsTypeReference' && tsType.typeName?.type === 'Identifier') {
|
|
600
634
|
const name = tsType.typeName.value;
|
|
601
635
|
if (name !== 'Array' && name !== 'ReadonlyArray')
|
|
@@ -607,6 +641,74 @@ class ExpressionResolver {
|
|
|
607
641
|
catch { }
|
|
608
642
|
return undefined;
|
|
609
643
|
}
|
|
644
|
+
// `['day', 'hour']` -> ['day', 'hour']
|
|
645
|
+
arrayLiteralValues(arr) {
|
|
646
|
+
const vals = [];
|
|
647
|
+
for (const elem of arr.elements ?? []) {
|
|
648
|
+
if (!elem?.expression)
|
|
649
|
+
continue;
|
|
650
|
+
const resolved = this.resolvePossibleStringValuesFromExpression(elem.expression);
|
|
651
|
+
if (resolved.length === 1)
|
|
652
|
+
vals.push(resolved[0]);
|
|
653
|
+
}
|
|
654
|
+
return vals.length > 0 ? vals : undefined;
|
|
655
|
+
}
|
|
656
|
+
// `[{ unit: 'day' }, { unit: 'hour' }]` -> { unit: ['day', 'hour'] }
|
|
657
|
+
arrayLiteralMembers(arr) {
|
|
658
|
+
const members = {};
|
|
659
|
+
for (const elem of arr.elements ?? []) {
|
|
660
|
+
const objExpr = unwrapExpr(elem?.expression);
|
|
661
|
+
if (objExpr?.type !== 'ObjectExpression')
|
|
662
|
+
continue;
|
|
663
|
+
for (const p of (objExpr.properties ?? [])) {
|
|
664
|
+
if (p?.type !== 'KeyValueProperty')
|
|
665
|
+
continue;
|
|
666
|
+
const keyName = p.key?.type === 'Identifier' || p.key?.type === 'StringLiteral' ? p.key.value : undefined;
|
|
667
|
+
if (!keyName)
|
|
668
|
+
continue;
|
|
669
|
+
const resolved = this.resolvePossibleStringValuesFromExpression(p.value);
|
|
670
|
+
if (resolved.length !== 1)
|
|
671
|
+
continue;
|
|
672
|
+
const list = members[keyName] ??= [];
|
|
673
|
+
if (!list.includes(resolved[0]))
|
|
674
|
+
list.push(resolved[0]);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return Object.keys(members).length > 0 ? members : undefined;
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
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`).
|
|
682
|
+
*/
|
|
683
|
+
arrayValuesOf(expr) {
|
|
684
|
+
expr = unwrapExpr(expr);
|
|
685
|
+
if (expr?.type === 'Identifier')
|
|
686
|
+
return this.getVariableValues(expr.value);
|
|
687
|
+
if (expr?.type === 'ArrayExpression')
|
|
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
|
+
}
|
|
694
|
+
return undefined;
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* The element member map of an iterated array of objects: a typed or constant
|
|
698
|
+
* identifier (`items: IProps[]`), an inline literal (`[{ unit: 'day' }]`) or a
|
|
699
|
+
* typed member (`props.items`).
|
|
700
|
+
*/
|
|
701
|
+
arrayMembersOf(expr) {
|
|
702
|
+
expr = unwrapExpr(expr);
|
|
703
|
+
if (expr?.type === 'Identifier')
|
|
704
|
+
return this.arrayElementMembers.get(expr.value);
|
|
705
|
+
if (expr?.type === 'ArrayExpression')
|
|
706
|
+
return this.arrayLiteralMembers(expr);
|
|
707
|
+
// `props.items` where `items: Item[]`
|
|
708
|
+
if (expr?.type === 'MemberExpression')
|
|
709
|
+
return this.objectMembersOf(expr);
|
|
710
|
+
return undefined;
|
|
711
|
+
}
|
|
610
712
|
/**
|
|
611
713
|
* Bind an identifier to the member map of its array element type
|
|
612
714
|
* (`items: IProps[]`).
|
|
@@ -614,9 +716,6 @@ class ExpressionResolver {
|
|
|
614
716
|
setArrayElementMembers(name, members) {
|
|
615
717
|
this.arrayElementMembers.set(name, members);
|
|
616
718
|
}
|
|
617
|
-
getArrayElementMembers(name) {
|
|
618
|
-
return this.arrayElementMembers.get(name);
|
|
619
|
-
}
|
|
620
719
|
deleteArrayElementMembers(name) {
|
|
621
720
|
this.arrayElementMembers.delete(name);
|
|
622
721
|
}
|
|
@@ -887,6 +986,10 @@ class ExpressionResolver {
|
|
|
887
986
|
resolvePossibleStringValuesFromExpression(expression, returnEmptyStrings = false) {
|
|
888
987
|
// `t(('key'))` / `t(cond ? 'a' : ('b'))`: parens are just a wrapper node (#295).
|
|
889
988
|
expression = astUtils.unwrapParens(expression);
|
|
989
|
+
// `pet.category?.kind` → `pet.category.kind`
|
|
990
|
+
if (expression.type === 'OptionalChainingExpression') {
|
|
991
|
+
return this.resolvePossibleStringValuesFromExpression(expression.base, returnEmptyStrings);
|
|
992
|
+
}
|
|
890
993
|
// Support selector-style arrow functions used by the selector API:
|
|
891
994
|
// e.g. ($) => $.path.to.key -> ['path.to.key']
|
|
892
995
|
// e.g. ($) => $.table.columns[field] -> ['table.columns.name', 'table.columns.age']
|
|
@@ -1206,6 +1309,11 @@ class ExpressionResolver {
|
|
|
1206
1309
|
}
|
|
1207
1310
|
}
|
|
1208
1311
|
}
|
|
1312
|
+
// `DeepObject['Bar']['status']` → that member's values
|
|
1313
|
+
const key = indexedKey(type);
|
|
1314
|
+
const vals = key === undefined ? undefined : this.resolveTypeMembers(type.objectType)?.[key];
|
|
1315
|
+
if (vals)
|
|
1316
|
+
return vals;
|
|
1209
1317
|
}
|
|
1210
1318
|
catch { }
|
|
1211
1319
|
}
|
|
@@ -1295,3 +1403,4 @@ class ExpressionResolver {
|
|
|
1295
1403
|
}
|
|
1296
1404
|
|
|
1297
1405
|
exports.ExpressionResolver = ExpressionResolver;
|
|
1406
|
+
exports.nestedMembers = nestedMembers;
|