Skip to content

Fix require() inside functions being treated as imports#1247

Merged
misrasaurabh1 merged 1 commit intomainfrom
fix/require-inside-function-not-import
Feb 2, 2026
Merged

Fix require() inside functions being treated as imports#1247
misrasaurabh1 merged 1 commit intomainfrom
fix/require-inside-function-not-import

Conversation

@misrasaurabh1
Copy link
Contributor

Summary

  • Fixed a bug where dynamic require() calls inside function/method bodies were incorrectly treated as module-level imports
  • This caused invalid code to be sent to the AI service, resulting in "Invalid TypeScript: Invalid syntax" errors
  • Root cause: the tree traversal for finding imports didn't exclude function bodies

Example

The code:

class BloomFilter {
    export() {
        const gzipSize = (
            require('next/dist/compiled/gzip-size') as typeof import('next/dist/compiled/gzip-size')
        ).sync(filterData)
    }
}

Would incorrectly extract require('next/dist/compiled/gzip-size') as typeof import('next/dist/compiled/gzip-size') as an import, which when added to the top of the file creates invalid syntax.

Test plan

  • Added test test_require_inside_function_not_import
  • All 44 existing treesitter_utils tests pass
  • Verified that the bloom-filter.ts export method no longer causes invalid syntax errors

🤖 Generated with Claude Code

When extracting imports from JavaScript/TypeScript code, dynamic
require() calls inside function bodies were incorrectly being
extracted as module-level imports. This caused invalid code to be
sent to the AI service for optimization.

For example, the code:
```
function foo() {
    const mod = require('module') as typeof import('module');
}
```

Would have `require('module') as typeof import('module')` extracted
as an import statement, which when added to the top of the code
would create invalid syntax.

The fix tracks when we enter function/method bodies during tree
traversal and only treats require() calls as imports when they
are at module level.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@misrasaurabh1 misrasaurabh1 merged commit d557e74 into main Feb 2, 2026
23 of 27 checks passed
@misrasaurabh1 misrasaurabh1 deleted the fix/require-inside-function-not-import branch February 2, 2026 00:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant