@@ -21,6 +21,8 @@ export type CreateRequireUsage = CreateRequireSpecifier & {
2121
2222const IDENTIFIER = "[A-Za-z_$][\\w$]*" ;
2323const STRING_LITERAL = `(["'])([^"'\\n]+)\\1` ;
24+ const NESTED_CALL_ARGS = `(?:[^()]|\\([^()]*\\))*` ;
25+ const MODULE_IMPORT_REGEX = / (?: f r o m \s * | r e q u i r e \( \s * | i m p o r t \( \s * ) [ " ' ] (?: n o d e : ) ? m o d u l e [ " ' ] / ;
2426
2527/**
2628 * Finds string-literal package specifiers loaded through `createRequire`, e.g.
@@ -33,13 +35,13 @@ const STRING_LITERAL = `(["'])([^"'\\n]+)\\1`;
3335 * computed specifiers or a re-exported `createRequire` are not detected.
3436 */
3537export function scanSourceForCreateRequire ( source : string ) : CreateRequireSpecifier [ ] {
36- if ( ! source . includes ( "createRequire" ) ) {
38+ if ( ! source . includes ( "createRequire" ) || ! MODULE_IMPORT_REGEX . test ( source ) ) {
3739 return [ ] ;
3840 }
3941
4042 const aliases = collectCreateRequireAliases ( source ) ;
4143 const aliasPattern = Array . from ( aliases ) . map ( escapeRegExp ) . join ( "|" ) ;
42- const createRequireCall = `(?:${ IDENTIFIER } \\s*\\.\\s*)?(?:${ aliasPattern } )\\s*\\([^()]* \\)` ;
44+ const createRequireCall = `(?:${ IDENTIFIER } \\s*\\.\\s*)?(?:${ aliasPattern } )\\s*\\(${ NESTED_CALL_ARGS } \\)` ;
4345
4446 const results : CreateRequireSpecifier [ ] = [ ] ;
4547 const seen = new Set < string > ( ) ;
@@ -51,8 +53,14 @@ export function scanSourceForCreateRequire(source: string): CreateRequireSpecifi
5153 return ;
5254 }
5355
56+ const location = locationAt ( source , index ) ;
57+
58+ if ( isCommentedOut ( location . lineText , location . column ) ) {
59+ return ;
60+ }
61+
5462 seen . add ( key ) ;
55- results . push ( { specifier, ...locationAt ( source , index ) } ) ;
63+ results . push ( { specifier, ...location } ) ;
5664 } ;
5765
5866 const directCallRegex = new RegExp (
@@ -137,6 +145,21 @@ function isWarnableSpecifier(specifier: string): boolean {
137145 return ! builtinModules . includes ( packageNameForSpecifier ( specifier ) ) ;
138146}
139147
148+ /**
149+ * Line-level heuristic for hits inside comments (commented-out code is the
150+ * realistic false-positive source). A `//` or `/*` before the hit on the same
151+ * line, or a line shaped like a block-comment continuation, means skip.
152+ */
153+ function isCommentedOut ( lineText : string , column : number ) : boolean {
154+ const prefix = lineText . slice ( 0 , column ) ;
155+
156+ if ( prefix . includes ( "//" ) || prefix . includes ( "/*" ) ) {
157+ return true ;
158+ }
159+
160+ return lineText . trimStart ( ) . startsWith ( "*" ) ;
161+ }
162+
140163function locationAt (
141164 source : string ,
142165 index : number
0 commit comments