gtx-cli 2.5.0-alpha.3 → 2.5.1

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/config/generateSettings.js +8 -1
  3. package/dist/console/colors.d.ts +1 -0
  4. package/dist/console/colors.js +3 -0
  5. package/dist/console/index.d.ts +8 -0
  6. package/dist/console/index.js +15 -2
  7. package/dist/react/jsx/evaluateJsx.d.ts +9 -6
  8. package/dist/react/jsx/evaluateJsx.js +33 -5
  9. package/dist/react/jsx/utils/buildImportMap.d.ts +9 -0
  10. package/dist/react/jsx/utils/buildImportMap.js +30 -0
  11. package/dist/react/jsx/utils/constants.d.ts +2 -0
  12. package/dist/react/jsx/utils/constants.js +11 -2
  13. package/dist/react/jsx/utils/getPathsAndAliases.d.ts +17 -0
  14. package/dist/react/jsx/utils/getPathsAndAliases.js +89 -0
  15. package/dist/react/{data-_gt → jsx/utils/jsxParsing}/addGTIdentifierToSyntaxTree.d.ts +2 -1
  16. package/dist/react/{data-_gt → jsx/utils/jsxParsing}/addGTIdentifierToSyntaxTree.js +30 -6
  17. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.d.ts +6 -0
  18. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.js +199 -0
  19. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.d.ts +13 -0
  20. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.js +42 -0
  21. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.d.ts +5 -0
  22. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.js +69 -0
  23. package/dist/react/jsx/utils/jsxParsing/parseJsx.d.ts +61 -0
  24. package/dist/react/jsx/utils/jsxParsing/parseJsx.js +1015 -0
  25. package/dist/react/jsx/utils/jsxParsing/parseTProps.d.ts +8 -0
  26. package/dist/react/jsx/utils/jsxParsing/parseTProps.js +47 -0
  27. package/dist/react/jsx/utils/jsxParsing/removeNullChildrenFields.d.ts +2 -0
  28. package/dist/react/jsx/utils/jsxParsing/removeNullChildrenFields.js +61 -0
  29. package/dist/react/jsx/utils/jsxParsing/types.d.ts +48 -0
  30. package/dist/react/jsx/utils/jsxParsing/types.js +34 -0
  31. package/dist/react/jsx/utils/parseStringFunction.js +4 -141
  32. package/dist/react/jsx/utils/resolveImportPath.d.ts +11 -0
  33. package/dist/react/jsx/utils/resolveImportPath.js +111 -0
  34. package/dist/react/parse/createInlineUpdates.js +19 -70
  35. package/package.json +2 -2
  36. package/dist/react/jsx/trimJsxStringChildren.d.ts +0 -7
  37. package/dist/react/jsx/trimJsxStringChildren.js +0 -122
  38. package/dist/react/jsx/utils/parseJsx.d.ts +0 -21
  39. package/dist/react/jsx/utils/parseJsx.js +0 -259
@@ -0,0 +1,1015 @@
1
+ import generateModule from '@babel/generator';
2
+ // Handle CommonJS/ESM interop
3
+ const generate = generateModule.default || generateModule;
4
+ import * as t from '@babel/types';
5
+ import fs from 'node:fs';
6
+ import { parse } from '@babel/parser';
7
+ import addGTIdentifierToSyntaxTree from './addGTIdentifierToSyntaxTree.js';
8
+ import { warnHasUnwrappedExpressionSync, warnNestedTComponent, warnInvalidStaticChildSync, warnFunctionNotFoundSync, warnMissingReturnSync, warnDuplicateFunctionDefinitionSync, warnInvalidStaticInitSync, warnRecursiveFunctionCallSync, } from '../../../../console/index.js';
9
+ import { isAcceptedPluralForm } from 'generaltranslation/internal';
10
+ import { isStaticExpression } from '../../evaluateJsx.js';
11
+ import { STATIC_COMPONENT, TRANSLATION_COMPONENT, VARIABLE_COMPONENTS, } from '../constants.js';
12
+ import { HTML_CONTENT_PROPS } from 'generaltranslation/types';
13
+ import { resolveImportPath } from '../resolveImportPath.js';
14
+ import traverseModule from '@babel/traverse';
15
+ import { buildImportMap } from '../buildImportMap.js';
16
+ import { getPathsAndAliases } from '../getPathsAndAliases.js';
17
+ import { parseTProps } from './parseTProps.js';
18
+ import { handleChildrenWhitespace } from './handleChildrenWhitespace.js';
19
+ import { isElementNode, } from './types.js';
20
+ import { multiplyJsxTree } from './multiplication/multiplyJsxTree.js';
21
+ import { removeNullChildrenFields } from './removeNullChildrenFields.js';
22
+ // Handle CommonJS/ESM interop
23
+ const traverse = traverseModule.default || traverseModule;
24
+ // TODO: currently we cover VariableDeclaration and FunctionDeclaration nodes, but are there others we should cover as well?
25
+ /**
26
+ * Cache for resolved import paths to avoid redundant I/O operations.
27
+ * Key: `${currentFile}::${importPath}`
28
+ * Value: resolved absolute path or null
29
+ */
30
+ const resolveImportPathCache = new Map();
31
+ /**
32
+ * Cache for processed functions to avoid re-parsing the same files.
33
+ * Key: `${filePath}::${functionName}::${argIndex}`
34
+ * Value: boolean indicating whether the function was found and processed
35
+ */
36
+ const processFunctionCache = new Map();
37
+ /**
38
+ * Entry point for JSX parsing
39
+ */
40
+ export function parseTranslationComponent({ originalName, importAliases, localName, path, updates, errors, warnings, file, parsingOptions, pkg, }) {
41
+ // First, collect all imports in this file to track cross-file function calls
42
+ const importedFunctionsMap = buildImportMap(path.scope.getProgramParent().path);
43
+ const referencePaths = path.scope.bindings[localName]?.referencePaths || [];
44
+ for (const refPath of referencePaths) {
45
+ // Only start at opening tag
46
+ if (!t.isJSXOpeningElement(refPath.parent) ||
47
+ !refPath.parentPath?.parentPath) {
48
+ continue;
49
+ }
50
+ // Get the JSX element NodePath
51
+ const jsxElementPath = refPath.parentPath
52
+ ?.parentPath;
53
+ // Parse <T> component
54
+ parseJSXElement({
55
+ scopeNode: jsxElementPath,
56
+ node: jsxElementPath.node,
57
+ pkg,
58
+ originalName,
59
+ importAliases,
60
+ updates,
61
+ errors,
62
+ warnings,
63
+ file,
64
+ parsingOptions,
65
+ importedFunctionsMap,
66
+ });
67
+ }
68
+ }
69
+ /**
70
+ * Builds a JSX tree from a given node, recursively handling children.
71
+ * @param node - The node to build the tree from
72
+ * @param unwrappedExpressions - An array to store unwrapped expressions
73
+ * @param updates - The updates array
74
+ * @param errors - The errors array
75
+ * @param file - The file name
76
+ * @param insideT - Whether the current node is inside a <T> component
77
+ * @returns The built JSX tree
78
+ */
79
+ export function buildJSXTree({ importAliases, node, unwrappedExpressions, visited, callStack, updates, errors, warnings, file, insideT, parsingOptions, scopeNode, importedFunctionsMap, pkg, }) {
80
+ if (t.isJSXExpressionContainer(node)) {
81
+ // Skip JSX comments
82
+ if (t.isJSXEmptyExpression(node.expression)) {
83
+ return null;
84
+ }
85
+ const expr = node.expression;
86
+ if (t.isJSXElement(expr)) {
87
+ return buildJSXTree({
88
+ importAliases,
89
+ node: expr,
90
+ unwrappedExpressions,
91
+ visited,
92
+ callStack,
93
+ updates,
94
+ errors: errors,
95
+ warnings: warnings,
96
+ file,
97
+ insideT,
98
+ parsingOptions,
99
+ scopeNode,
100
+ importedFunctionsMap,
101
+ pkg,
102
+ });
103
+ }
104
+ const staticAnalysis = isStaticExpression(expr, true);
105
+ if (staticAnalysis.isStatic && staticAnalysis.value !== undefined) {
106
+ // Preserve the exact whitespace for static string expressions
107
+ return {
108
+ nodeType: 'expression',
109
+ result: staticAnalysis.value,
110
+ };
111
+ }
112
+ // Keep existing behavior for non-static expressions
113
+ const code = generate(node).code;
114
+ unwrappedExpressions.push(code); // Keep track of unwrapped expressions for error reporting
115
+ return code;
116
+ }
117
+ else if (t.isJSXText(node)) {
118
+ // Updated JSX Text handling
119
+ // JSX Text handling following React's rules
120
+ const text = node.value;
121
+ return text;
122
+ }
123
+ else if (t.isJSXElement(node)) {
124
+ const element = node;
125
+ const elementName = element.openingElement.name;
126
+ let typeName;
127
+ if (t.isJSXIdentifier(elementName)) {
128
+ typeName = elementName.name;
129
+ }
130
+ else if (t.isJSXMemberExpression(elementName)) {
131
+ typeName = generate(elementName).code;
132
+ }
133
+ else {
134
+ typeName = null;
135
+ }
136
+ // Convert from alias to original name
137
+ const componentType = importAliases[typeName ?? ''];
138
+ if (componentType === TRANSLATION_COMPONENT && insideT) {
139
+ // Add warning: Nested <T> components are allowed, but they are advised against
140
+ warnings.add(warnNestedTComponent(file, `${element.loc?.start?.line}:${element.loc?.start?.column}`));
141
+ }
142
+ // If this JSXElement is one of the recognized variable components,
143
+ const elementIsVariable = VARIABLE_COMPONENTS.includes(componentType);
144
+ const props = {};
145
+ const elementIsPlural = componentType === 'Plural';
146
+ const elementIsBranch = componentType === 'Branch';
147
+ element.openingElement.attributes.forEach((attr) => {
148
+ if (t.isJSXAttribute(attr)) {
149
+ const attrName = attr.name.name;
150
+ let attrValue = null;
151
+ if (attr.value) {
152
+ if (t.isStringLiteral(attr.value)) {
153
+ attrValue = attr.value.value;
154
+ }
155
+ else if (t.isJSXExpressionContainer(attr.value)) {
156
+ // Check if this is an HTML content prop (title, placeholder, alt, etc.)
157
+ const isHtmlContentProp = Object.values(HTML_CONTENT_PROPS).includes(attrName);
158
+ if (isHtmlContentProp) {
159
+ // For HTML content props, only accept static string expressions
160
+ const staticAnalysis = isStaticExpression(attr.value.expression, true);
161
+ if (staticAnalysis.isStatic &&
162
+ staticAnalysis.value !== undefined) {
163
+ attrValue = staticAnalysis.value;
164
+ }
165
+ // Otherwise attrValue stays null and won't be included
166
+ }
167
+ else {
168
+ // For non-HTML-content props, validate plural/branch then build tree
169
+ if ((elementIsPlural && isAcceptedPluralForm(attrName)) ||
170
+ (elementIsBranch && attrName !== 'branch')) {
171
+ // Make sure that variable strings like {`I have ${count} book`} are invalid!
172
+ if (t.isTemplateLiteral(attr.value.expression) &&
173
+ !isStaticExpression(attr.value.expression, true).isStatic) {
174
+ unwrappedExpressions.push(generate(attr.value).code);
175
+ }
176
+ // If it's an array, flag as an unwrapped expression
177
+ if (t.isArrayExpression(attr.value.expression)) {
178
+ unwrappedExpressions.push(generate(attr.value.expression).code);
179
+ }
180
+ }
181
+ attrValue = buildJSXTree({
182
+ importAliases,
183
+ node: attr.value.expression,
184
+ unwrappedExpressions,
185
+ visited,
186
+ callStack,
187
+ updates,
188
+ errors: errors,
189
+ warnings: warnings,
190
+ file: file,
191
+ insideT: true,
192
+ parsingOptions,
193
+ scopeNode,
194
+ importedFunctionsMap,
195
+ pkg,
196
+ });
197
+ }
198
+ }
199
+ }
200
+ props[attrName] = attrValue;
201
+ }
202
+ });
203
+ if (elementIsVariable) {
204
+ if (componentType === STATIC_COMPONENT) {
205
+ return resolveStaticComponentChildren({
206
+ importAliases,
207
+ scopeNode,
208
+ children: element.children,
209
+ unwrappedExpressions,
210
+ visited,
211
+ updates,
212
+ errors,
213
+ warnings,
214
+ file,
215
+ callStack,
216
+ parsingOptions,
217
+ importedFunctionsMap,
218
+ pkg,
219
+ props,
220
+ });
221
+ }
222
+ // I do not see why this is being called, i am disabling this for now:
223
+ // parseJSXElement({
224
+ // importAliases,
225
+ // node: element,
226
+ // updates,
227
+ // errors,
228
+ // warnings,
229
+ // file,
230
+ // parsingOptions,
231
+ // });
232
+ return {
233
+ nodeType: 'element',
234
+ // if componentType is undefined, use typeName
235
+ // Basically, if componentType is not a GT component, use typeName such as <div>
236
+ type: componentType ?? typeName ?? '',
237
+ props,
238
+ };
239
+ }
240
+ const children = element.children
241
+ .map((child) => buildJSXTree({
242
+ importAliases,
243
+ node: child,
244
+ unwrappedExpressions,
245
+ visited,
246
+ callStack,
247
+ updates,
248
+ errors,
249
+ warnings,
250
+ file,
251
+ insideT: true,
252
+ parsingOptions,
253
+ scopeNode,
254
+ importedFunctionsMap,
255
+ pkg,
256
+ }))
257
+ .filter((child) => child !== null && child !== '');
258
+ if (children.length === 1) {
259
+ props.children = children[0];
260
+ }
261
+ else if (children.length > 1) {
262
+ props.children = children;
263
+ }
264
+ return {
265
+ nodeType: 'element',
266
+ // if componentType is undefined, use typeName
267
+ // Basically, if componentType is not a GT component, use typeName such as <div>
268
+ type: componentType ?? typeName,
269
+ props,
270
+ };
271
+ }
272
+ // If it's a JSX fragment
273
+ else if (t.isJSXFragment(node)) {
274
+ const children = node.children
275
+ .map((child) => buildJSXTree({
276
+ importAliases,
277
+ node: child,
278
+ unwrappedExpressions,
279
+ visited,
280
+ callStack,
281
+ updates,
282
+ errors,
283
+ warnings,
284
+ file,
285
+ insideT: true,
286
+ parsingOptions,
287
+ scopeNode,
288
+ importedFunctionsMap,
289
+ pkg,
290
+ }))
291
+ .filter((child) => child !== null && child !== '');
292
+ const props = {};
293
+ if (children.length === 1) {
294
+ props.children = children[0];
295
+ }
296
+ else if (children.length > 1) {
297
+ props.children = children;
298
+ }
299
+ return {
300
+ nodeType: 'element',
301
+ type: '',
302
+ props,
303
+ };
304
+ }
305
+ // If it's a string literal (standalone)
306
+ else if (t.isStringLiteral(node)) {
307
+ return node.value;
308
+ }
309
+ // If it's a template literal
310
+ else if (t.isTemplateLiteral(node)) {
311
+ // We've already checked that it's static, and and added a warning if it's not, this check is just for fallback behavior
312
+ if (!isStaticExpression(node, true).isStatic ||
313
+ node.quasis[0].value.cooked === undefined) {
314
+ return generate(node).code;
315
+ }
316
+ return node.quasis[0].value.cooked;
317
+ }
318
+ else if (t.isNullLiteral(node)) {
319
+ // If it's null, return null
320
+ return null;
321
+ }
322
+ else if (t.isBooleanLiteral(node)) {
323
+ // If it's a boolean, return the boolean
324
+ return node.value;
325
+ }
326
+ else if (t.isNumericLiteral(node)) {
327
+ // If it's a number, return the number
328
+ return node.value.toString();
329
+ }
330
+ // Negative
331
+ else if (t.isUnaryExpression(node)) {
332
+ // If it's a unary expression, return the expression
333
+ const staticAnalysis = isStaticExpression(node, true);
334
+ if (staticAnalysis.isStatic && staticAnalysis.value !== undefined) {
335
+ return staticAnalysis.value;
336
+ }
337
+ return generate(node).code;
338
+ }
339
+ // If it's some other JS expression
340
+ else if (t.isIdentifier(node) ||
341
+ t.isMemberExpression(node) ||
342
+ t.isCallExpression(node) ||
343
+ t.isBinaryExpression(node) ||
344
+ t.isLogicalExpression(node) ||
345
+ t.isConditionalExpression(node)) {
346
+ return generate(node).code;
347
+ }
348
+ else {
349
+ return generate(node).code;
350
+ }
351
+ }
352
+ // end buildJSXTree
353
+ // Parses a JSX element and adds it to the updates array
354
+ export function parseJSXElement({ importAliases, node, originalName, pkg, updates, errors, warnings, file, parsingOptions, scopeNode, importedFunctionsMap, }) {
355
+ const openingElement = node.openingElement;
356
+ const name = openingElement.name;
357
+ // Only proceed if it's <T> ...
358
+ // TODO: i don't think this condition is needed anymore
359
+ if (!(name.type === 'JSXIdentifier' && originalName === TRANSLATION_COMPONENT)) {
360
+ return;
361
+ }
362
+ const componentErrors = [];
363
+ const componentWarnings = new Set();
364
+ const metadata = {};
365
+ // We'll track this flag to know if any unwrapped {variable} is found in children
366
+ const unwrappedExpressions = [];
367
+ // Gather <T>'s props
368
+ parseTProps({
369
+ openingElement,
370
+ metadata,
371
+ componentErrors,
372
+ file,
373
+ });
374
+ // Build the JSX tree for this component
375
+ const treeResult = buildJSXTree({
376
+ importAliases,
377
+ node,
378
+ scopeNode,
379
+ visited: new Set(),
380
+ callStack: [],
381
+ pkg,
382
+ unwrappedExpressions,
383
+ updates,
384
+ errors: componentErrors,
385
+ warnings: componentWarnings,
386
+ file,
387
+ insideT: false,
388
+ parsingOptions,
389
+ importedFunctionsMap,
390
+ });
391
+ // Strip the outer <T> component if necessary
392
+ const jsxTree = isElementNode(treeResult) && treeResult.props?.children
393
+ ? // We know this b/c the direct children of <T> will never be a multiplication node
394
+ treeResult.props.children
395
+ : treeResult;
396
+ // Update warnings
397
+ if (componentWarnings.size > 0) {
398
+ componentWarnings.forEach((warning) => warnings.add(warning));
399
+ }
400
+ // Update errors
401
+ if (componentErrors.length > 0) {
402
+ errors.push(...componentErrors);
403
+ return;
404
+ }
405
+ // Handle whitespace in children
406
+ const whitespaceHandledTree = handleChildrenWhitespace(jsxTree);
407
+ // Multiply the tree
408
+ const multipliedTrees = multiplyJsxTree(whitespaceHandledTree);
409
+ // Add GT identifiers to the tree
410
+ // TODO: do this in parallel
411
+ const minifiedTress = [];
412
+ for (const multipliedTree of multipliedTrees) {
413
+ const minifiedTree = addGTIdentifierToSyntaxTree(multipliedTree);
414
+ minifiedTress.push(Array.isArray(minifiedTree) && minifiedTree.length === 1
415
+ ? minifiedTree[0]
416
+ : minifiedTree);
417
+ }
418
+ // If we found an unwrapped expression, skip
419
+ if (unwrappedExpressions.length > 0) {
420
+ errors.push(warnHasUnwrappedExpressionSync(file, unwrappedExpressions, metadata.id, `${node.loc?.start?.line}:${node.loc?.start?.column}`));
421
+ return;
422
+ }
423
+ // <T> is valid here
424
+ for (const minifiedTree of minifiedTress) {
425
+ // Clean the tree by removing null 'c' fields from JsxElements
426
+ const cleanedTree = removeNullChildrenFields(minifiedTree);
427
+ updates.push({
428
+ dataFormat: 'JSX',
429
+ source: cleanedTree,
430
+ // eslint-disable-next-line no-undef
431
+ metadata: { ...structuredClone(metadata) },
432
+ });
433
+ }
434
+ }
435
+ /**
436
+ * Resolves an invocation inside of a <Static> component. It will resolve the function, and build
437
+ * a jsx tree for each return inside of the function definition.
438
+ *
439
+ * function getOtherSubject() {
440
+ * return <div>Jane</div>;
441
+ * }
442
+ *
443
+ * function getSubject() {
444
+ * if (condition) return getOtherSubject();
445
+ * return <div>John</div>;
446
+ * }
447
+ * ...
448
+ * <Static>
449
+ * {getSubject()}
450
+ * </Static>
451
+ */
452
+ function resolveStaticComponentChildren({ importAliases, scopeNode, children, unwrappedExpressions, visited, updates, errors, warnings, file, callStack, parsingOptions, importedFunctionsMap, pkg, props, }) {
453
+ const result = {
454
+ nodeType: 'element',
455
+ type: STATIC_COMPONENT,
456
+ props,
457
+ };
458
+ let found = false;
459
+ // Create children array if necessary
460
+ if (children.length) {
461
+ result.props.children = [];
462
+ }
463
+ for (const child of children) {
464
+ // Ignore whitespace outside of jsx container
465
+ if (t.isJSXText(child) && child.value.trim() === '') {
466
+ result.props.children.push(child.value);
467
+ continue;
468
+ }
469
+ // Must be an expression container with a function invocation
470
+ if (!t.isJSXExpressionContainer(child) ||
471
+ !((t.isCallExpression(child.expression) &&
472
+ t.isIdentifier(child.expression.callee)) ||
473
+ (t.isAwaitExpression(child.expression) &&
474
+ t.isCallExpression(child.expression.argument) &&
475
+ t.isIdentifier(child.expression.argument.callee))) ||
476
+ found // There can only be one invocation inside of a <Static> component
477
+ ) {
478
+ errors.push(warnInvalidStaticChildSync(file, `${child.loc?.start?.line}:${child.loc?.start?.column}`));
479
+ continue;
480
+ }
481
+ // Set found to true
482
+ found = true;
483
+ // Get callee and binding from scope
484
+ const callee = (t.isAwaitExpression(child.expression)
485
+ ? child.expression.argument.callee
486
+ : child.expression.callee);
487
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
488
+ if (!calleeBinding) {
489
+ warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`);
490
+ continue;
491
+ }
492
+ // Function is found locally, return wrapped in an expression
493
+ const staticFunctionInvocation = resolveStaticFunctionInvocationFromBinding({
494
+ importAliases,
495
+ calleeBinding,
496
+ callee,
497
+ visited,
498
+ callStack,
499
+ file,
500
+ updates,
501
+ errors,
502
+ warnings,
503
+ unwrappedExpressions,
504
+ pkg,
505
+ parsingOptions,
506
+ importedFunctionsMap,
507
+ });
508
+ result.props.children.push({
509
+ nodeType: 'expression',
510
+ result: staticFunctionInvocation,
511
+ });
512
+ }
513
+ return result;
514
+ }
515
+ function resolveStaticFunctionInvocationFromBinding({ importAliases, calleeBinding, callee, unwrappedExpressions, visited, callStack, file, updates, errors, warnings, parsingOptions, importedFunctionsMap, pkg, }) {
516
+ function withRecusionGuard({ cb, filename, functionName, }) {
517
+ const cacheKey = `${filename}::${functionName}`;
518
+ if (callStack.includes(cacheKey)) {
519
+ errors.push(warnRecursiveFunctionCallSync(file, functionName));
520
+ return null;
521
+ }
522
+ callStack.push(cacheKey);
523
+ const result = cb();
524
+ callStack.pop();
525
+ return result;
526
+ }
527
+ // check for recursive calls
528
+ if (calleeBinding.path.isFunctionDeclaration()) {
529
+ // Handle function declarations: function getSubject() { ... }
530
+ const functionName = callee.name;
531
+ const path = calleeBinding.path;
532
+ return withRecusionGuard({
533
+ filename: file,
534
+ functionName,
535
+ cb: () => processFunctionDeclarationNodePath({
536
+ importAliases,
537
+ functionName,
538
+ path,
539
+ unwrappedExpressions,
540
+ callStack,
541
+ updates,
542
+ errors,
543
+ warnings,
544
+ visited,
545
+ file,
546
+ parsingOptions,
547
+ importedFunctionsMap,
548
+ pkg,
549
+ }),
550
+ });
551
+ }
552
+ else if (calleeBinding.path.isVariableDeclarator() &&
553
+ calleeBinding.path.node.init &&
554
+ (t.isArrowFunctionExpression(calleeBinding.path.node.init) ||
555
+ t.isFunctionExpression(calleeBinding.path.node.init))) {
556
+ // Handle arrow functions assigned to variables: const getData = (t) => {...}
557
+ const functionName = callee.name;
558
+ const path = calleeBinding.path;
559
+ return withRecusionGuard({
560
+ filename: file,
561
+ functionName,
562
+ cb: () => processVariableDeclarationNodePath({
563
+ importAliases,
564
+ functionName,
565
+ path,
566
+ unwrappedExpressions,
567
+ updates,
568
+ callStack,
569
+ pkg,
570
+ errors,
571
+ visited,
572
+ warnings,
573
+ file,
574
+ parsingOptions,
575
+ importedFunctionsMap,
576
+ }),
577
+ });
578
+ }
579
+ else if (importedFunctionsMap.has(callee.name)) {
580
+ // Function is being imported
581
+ const importPath = importedFunctionsMap.get(callee.name);
582
+ const filePath = resolveImportPath(file, importPath, parsingOptions, resolveImportPathCache);
583
+ if (filePath) {
584
+ const functionName = callee.name;
585
+ return withRecusionGuard({
586
+ filename: file,
587
+ functionName,
588
+ cb: () => processFunctionInFile({
589
+ filePath,
590
+ functionName,
591
+ visited,
592
+ callStack,
593
+ unwrappedExpressions,
594
+ updates,
595
+ errors,
596
+ warnings,
597
+ file,
598
+ parsingOptions,
599
+ pkg,
600
+ }),
601
+ });
602
+ }
603
+ }
604
+ warnings.add(warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`));
605
+ return null;
606
+ }
607
+ /**
608
+ * Searches for a specific user-defined function in a file.
609
+ * This is the resolution logic
610
+ *
611
+ * Handles multiple function declaration patterns:
612
+ * - function getInfo() { ... }
613
+ * - export function getInfo() { ... }
614
+ * - const getInfo = () => { ... }
615
+ *
616
+ * If the function is not found in the file, follows re-exports (export * from './other')
617
+ */
618
+ function processFunctionInFile({ filePath, functionName, visited, callStack, parsingOptions, updates, errors, warnings, file, unwrappedExpressions, pkg, }) {
619
+ // Create a custom key for the function call
620
+ const cacheKey = `${filePath}::${functionName}`;
621
+ // Check cache first to avoid redundant parsing
622
+ if (processFunctionCache.has(cacheKey)) {
623
+ return processFunctionCache.get(cacheKey) ?? null;
624
+ }
625
+ // Prevent infinite loops from circular re-exports
626
+ if (visited.has(filePath)) {
627
+ return null;
628
+ }
629
+ visited.add(filePath);
630
+ let result = undefined;
631
+ try {
632
+ const code = fs.readFileSync(filePath, 'utf8');
633
+ const ast = parse(code, {
634
+ sourceType: 'module',
635
+ plugins: ['jsx', 'typescript'],
636
+ });
637
+ const { importAliases } = getPathsAndAliases(ast, pkg);
638
+ // Collect all imports in this file to track cross-file function calls
639
+ let importedFunctionsMap;
640
+ traverse(ast, {
641
+ Program(path) {
642
+ importedFunctionsMap = buildImportMap(path);
643
+ },
644
+ });
645
+ const reExports = [];
646
+ const warnDuplicateFuncDef = (path) => {
647
+ warnings.add(warnDuplicateFunctionDefinitionSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
648
+ };
649
+ traverse(ast, {
650
+ // Handle function declarations: function getInfo() { ... }
651
+ FunctionDeclaration(path) {
652
+ if (path.node.id?.name === functionName) {
653
+ if (result !== undefined)
654
+ return warnDuplicateFuncDef(path);
655
+ result = processFunctionDeclarationNodePath({
656
+ importAliases,
657
+ functionName,
658
+ path,
659
+ unwrappedExpressions,
660
+ callStack,
661
+ visited,
662
+ pkg,
663
+ updates,
664
+ errors,
665
+ warnings,
666
+ file,
667
+ parsingOptions,
668
+ importedFunctionsMap,
669
+ });
670
+ }
671
+ },
672
+ // Handle variable declarations: const getInfo = () => { ... }
673
+ VariableDeclarator(path) {
674
+ if (t.isIdentifier(path.node.id) &&
675
+ path.node.id.name === functionName &&
676
+ path.node.init &&
677
+ (t.isArrowFunctionExpression(path.node.init) ||
678
+ t.isFunctionExpression(path.node.init))) {
679
+ if (result !== undefined)
680
+ return warnDuplicateFuncDef(path);
681
+ result = processVariableDeclarationNodePath({
682
+ importAliases,
683
+ functionName,
684
+ path,
685
+ callStack,
686
+ pkg,
687
+ updates,
688
+ errors,
689
+ warnings,
690
+ visited,
691
+ unwrappedExpressions,
692
+ file,
693
+ parsingOptions,
694
+ importedFunctionsMap,
695
+ });
696
+ }
697
+ },
698
+ // Collect re-exports: export * from './other'
699
+ ExportAllDeclaration(path) {
700
+ if (t.isStringLiteral(path.node.source)) {
701
+ reExports.push(path.node.source.value);
702
+ }
703
+ },
704
+ // Collect named re-exports: export { foo } from './other'
705
+ ExportNamedDeclaration(path) {
706
+ if (path.node.source && t.isStringLiteral(path.node.source)) {
707
+ // Check if this export includes our function
708
+ const exportsFunction = path.node.specifiers.some((spec) => {
709
+ if (t.isExportSpecifier(spec)) {
710
+ const exportedName = t.isIdentifier(spec.exported)
711
+ ? spec.exported.name
712
+ : spec.exported.value;
713
+ return exportedName === functionName;
714
+ }
715
+ return false;
716
+ });
717
+ if (exportsFunction) {
718
+ reExports.push(path.node.source.value);
719
+ }
720
+ }
721
+ },
722
+ });
723
+ // If function not found, follow re-exports
724
+ if (result === undefined && reExports.length > 0) {
725
+ for (const reExportPath of reExports) {
726
+ const resolvedPath = resolveImportPath(filePath, reExportPath, parsingOptions, resolveImportPathCache);
727
+ if (resolvedPath) {
728
+ const foundResult = processFunctionInFile({
729
+ filePath: resolvedPath,
730
+ functionName,
731
+ unwrappedExpressions,
732
+ visited,
733
+ callStack,
734
+ parsingOptions,
735
+ updates,
736
+ errors,
737
+ warnings,
738
+ file,
739
+ pkg,
740
+ });
741
+ if (foundResult != null) {
742
+ result = foundResult;
743
+ break;
744
+ }
745
+ }
746
+ }
747
+ }
748
+ // Mark this function search as processed in the cache
749
+ processFunctionCache.set(cacheKey, result !== undefined ? result : null);
750
+ }
751
+ catch {
752
+ // Silently skip files that can't be parsed or accessed
753
+ // Still mark as processed to avoid retrying failed parses
754
+ processFunctionCache.set(cacheKey, null);
755
+ }
756
+ return result !== undefined ? result : null;
757
+ }
758
+ /**
759
+ * Process a function declaration
760
+ * function getInfo() { ... }
761
+ */
762
+ function processFunctionDeclarationNodePath({ functionName, path, importAliases, unwrappedExpressions, visited, callStack, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, pkg, }) {
763
+ const result = {
764
+ nodeType: 'multiplication',
765
+ branches: [],
766
+ };
767
+ path.traverse({
768
+ Function(path) {
769
+ path.skip();
770
+ },
771
+ ReturnStatement(returnPath) {
772
+ const returnNodePath = returnPath.get('argument');
773
+ if (!returnNodePath.isExpression()) {
774
+ return;
775
+ }
776
+ result.branches.push(processReturnExpression({
777
+ unwrappedExpressions,
778
+ functionName,
779
+ pkg,
780
+ callStack,
781
+ scopeNode: returnNodePath,
782
+ expressionNodePath: returnNodePath,
783
+ importAliases,
784
+ visited,
785
+ updates,
786
+ errors,
787
+ warnings,
788
+ file,
789
+ parsingOptions,
790
+ importedFunctionsMap,
791
+ }));
792
+ },
793
+ });
794
+ if (result.branches.length === 0) {
795
+ return null;
796
+ }
797
+ return result;
798
+ }
799
+ /**
800
+ * Process a variable declaration of a function
801
+ * const getInfo = () => { ... }
802
+ *
803
+ * IMPORTANT: the RHand value must be the function definition, or this will fail
804
+ */
805
+ function processVariableDeclarationNodePath({ functionName, path, importAliases, unwrappedExpressions, visited, callStack, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, pkg, }) {
806
+ const result = {
807
+ nodeType: 'multiplication',
808
+ branches: [],
809
+ };
810
+ // Enforce the Rhand is a function definition
811
+ const arrowFunctionPath = path.get('init');
812
+ if (!arrowFunctionPath.isArrowFunctionExpression()) {
813
+ errors.push(warnInvalidStaticInitSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
814
+ return null;
815
+ }
816
+ const bodyNodePath = arrowFunctionPath.get('body');
817
+ if (bodyNodePath.isExpression()) {
818
+ // process expression return
819
+ result.branches.push(processReturnExpression({
820
+ unwrappedExpressions,
821
+ functionName,
822
+ pkg,
823
+ scopeNode: arrowFunctionPath,
824
+ expressionNodePath: bodyNodePath,
825
+ importAliases,
826
+ visited,
827
+ callStack,
828
+ updates,
829
+ errors,
830
+ warnings,
831
+ file,
832
+ parsingOptions,
833
+ importedFunctionsMap,
834
+ }));
835
+ }
836
+ else {
837
+ // search for a return statement
838
+ bodyNodePath.traverse({
839
+ Function(path) {
840
+ path.skip();
841
+ },
842
+ ReturnStatement(returnPath) {
843
+ const returnNodePath = returnPath.get('argument');
844
+ if (!returnNodePath.isExpression()) {
845
+ return;
846
+ }
847
+ result.branches.push(processReturnExpression({
848
+ unwrappedExpressions,
849
+ functionName,
850
+ pkg,
851
+ scopeNode: returnPath,
852
+ expressionNodePath: returnNodePath,
853
+ importAliases,
854
+ visited,
855
+ callStack,
856
+ updates,
857
+ errors,
858
+ warnings,
859
+ file,
860
+ parsingOptions,
861
+ importedFunctionsMap,
862
+ }));
863
+ },
864
+ });
865
+ }
866
+ if (result.branches.length === 0) {
867
+ errors.push(warnMissingReturnSync(file, functionName, `${path.node.loc?.start?.line}:${path.node.loc?.start?.column}`));
868
+ return null;
869
+ }
870
+ return result;
871
+ }
872
+ /**
873
+ * Process a expression being returned from a function
874
+ */
875
+ function processReturnExpression({ unwrappedExpressions, scopeNode, expressionNodePath, importAliases, visited, callStack, updates, errors, warnings, file, parsingOptions, importedFunctionsMap, functionName, pkg, }) {
876
+ // // If the node is null, return
877
+ // if (expressionNodePath == null) return null;
878
+ // Remove parentheses if they exist
879
+ if (t.isParenthesizedExpression(expressionNodePath.node)) {
880
+ // ex: return (value)
881
+ return processReturnExpression({
882
+ unwrappedExpressions,
883
+ importAliases,
884
+ scopeNode,
885
+ expressionNodePath: expressionNodePath.get('expression'),
886
+ visited,
887
+ callStack,
888
+ updates,
889
+ errors,
890
+ warnings,
891
+ file,
892
+ parsingOptions,
893
+ functionName,
894
+ importedFunctionsMap,
895
+ pkg,
896
+ });
897
+ }
898
+ else if (t.isCallExpression(expressionNodePath.node) &&
899
+ t.isIdentifier(expressionNodePath.node.callee)) {
900
+ // ex: return someFunc()
901
+ const callee = expressionNodePath.node.callee;
902
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
903
+ if (!calleeBinding) {
904
+ warnings.add(warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`));
905
+ return null;
906
+ }
907
+ // Function is found locally
908
+ return resolveStaticFunctionInvocationFromBinding({
909
+ importAliases,
910
+ calleeBinding,
911
+ callee,
912
+ unwrappedExpressions,
913
+ callStack,
914
+ visited,
915
+ file,
916
+ updates,
917
+ errors,
918
+ warnings,
919
+ pkg,
920
+ parsingOptions,
921
+ importedFunctionsMap,
922
+ });
923
+ }
924
+ else if (t.isAwaitExpression(expressionNodePath.node) &&
925
+ t.isCallExpression(expressionNodePath.node.argument) &&
926
+ t.isIdentifier(expressionNodePath.node.argument.callee)) {
927
+ // ex: return await someFunc()
928
+ const callee = expressionNodePath.node.argument.callee;
929
+ const calleeBinding = scopeNode.scope.getBinding(callee.name);
930
+ if (!calleeBinding) {
931
+ warnings.add(warnFunctionNotFoundSync(file, callee.name, `${callee.loc?.start?.line}:${callee.loc?.start?.column}`));
932
+ return null;
933
+ }
934
+ // Function is found locally
935
+ return resolveStaticFunctionInvocationFromBinding({
936
+ importAliases,
937
+ calleeBinding,
938
+ callee,
939
+ unwrappedExpressions,
940
+ visited,
941
+ callStack,
942
+ file,
943
+ updates,
944
+ errors,
945
+ warnings,
946
+ pkg,
947
+ parsingOptions,
948
+ importedFunctionsMap,
949
+ });
950
+ }
951
+ else if (t.isJSXElement(expressionNodePath.node) ||
952
+ t.isJSXFragment(expressionNodePath.node)) {
953
+ // ex: return <div>Jsx content</div>
954
+ return buildJSXTree({
955
+ importAliases,
956
+ node: expressionNodePath.node,
957
+ unwrappedExpressions,
958
+ visited,
959
+ callStack,
960
+ updates,
961
+ errors,
962
+ warnings,
963
+ file,
964
+ insideT: true,
965
+ parsingOptions,
966
+ scopeNode,
967
+ importedFunctionsMap,
968
+ pkg,
969
+ });
970
+ }
971
+ else if (t.isConditionalExpression(expressionNodePath.node)) {
972
+ // ex: return condition ? <div>Jsx content</div> : <div>Jsx content</div>
973
+ // since two options here we must construct a new multiplication node
974
+ const consequentNodePath = expressionNodePath.get('consequent');
975
+ const alternateNodePath = expressionNodePath.get('alternate');
976
+ const result = {
977
+ nodeType: 'multiplication',
978
+ branches: [consequentNodePath, alternateNodePath].map((expressionNodePath) => processReturnExpression({
979
+ unwrappedExpressions,
980
+ importAliases,
981
+ scopeNode,
982
+ expressionNodePath,
983
+ visited,
984
+ callStack,
985
+ updates,
986
+ errors,
987
+ warnings,
988
+ file,
989
+ parsingOptions,
990
+ functionName,
991
+ importedFunctionsMap,
992
+ pkg,
993
+ })),
994
+ };
995
+ return result;
996
+ }
997
+ else {
998
+ return buildJSXTree({
999
+ importAliases,
1000
+ node: expressionNodePath.node,
1001
+ unwrappedExpressions,
1002
+ visited,
1003
+ callStack,
1004
+ updates,
1005
+ errors,
1006
+ warnings,
1007
+ file,
1008
+ insideT: true,
1009
+ parsingOptions,
1010
+ scopeNode,
1011
+ importedFunctionsMap,
1012
+ pkg,
1013
+ });
1014
+ }
1015
+ }