@@ -102,19 +102,34 @@ const rnImportShimInterop = id => (id && id.startsWith(`./${RN_IMPORT_SHIM_DIR}/
102102// name). Any other require in a shim could be shifted by the Metro bug when the package is missing. This
103103// catches imports of other packages, tslib helpers, and code shared between shims (Rollup moves it into a
104104// shared chunk that the shims require). The shim's own require() is plain code, so Rollup doesn't list it in
105- // chunk.imports; the generated code is checked instead.
105+ // chunk.imports; the generated code is parsed instead, with Rollup's parser .
106106const rnImportShimCheckPlugin = {
107107 name : 'rn-import-shim-check' ,
108108 generateBundle ( _ , bundle ) {
109+ // Module names of every require(...) call in an ESTree AST; a call whose argument is not a string is
110+ // listed as '<non-literal>'.
111+ const findRequireCalls = ( node , found = [ ] ) => {
112+ if ( Array . isArray ( node ) ) {
113+ node . forEach ( child => findRequireCalls ( child , found ) ) ;
114+ } else if ( node && typeof node . type === 'string' ) {
115+ if ( node . type === 'CallExpression' && node . callee . type === 'Identifier' && node . callee . name === 'require' ) {
116+ const [ arg ] = node . arguments ;
117+ found . push ( arg && arg . type === 'Literal' && typeof arg . value === 'string' ? arg . value : '<non-literal>' ) ;
118+ }
119+ for ( const value of Object . values ( node ) ) {
120+ if ( value && typeof value === 'object' ) findRequireCalls ( value , found ) ;
121+ }
122+ }
123+ return found ;
124+ } ;
125+
109126 for ( const chunk of Object . values ( bundle ) ) {
110127 if ( chunk . type !== 'chunk' ) continue ;
111- const requireCalls = chunk . code . match ( / \b r e q u i r e \s * \( / g) || [ ] ;
112- const requiredIds = [ ...chunk . code . matchAll ( / \b r e q u i r e \s * \( \s * [ ' " ] ( [ ^ ' " ] + ) [ ' " ] \s * \) / g) ] . map ( m => m [ 1 ] ) ;
113- const ok = chunk . isEntry && requireCalls . length === 1 && requiredIds . length === 1 && requiredIds [ 0 ] === chunk . name ;
114- if ( ! ok ) {
128+ const required = findRequireCalls ( this . parse ( chunk . code ) ) ;
129+ if ( ! chunk . isEntry || required . length !== 1 || required [ 0 ] !== chunk . name ) {
115130 this . error (
116131 `${ RN_IMPORT_SHIM_DIR } /${ chunk . fileName } : a shim must contain exactly one require(), of its own package` +
117- ` '${ chunk . name } ' (found: ${ requiredIds . join ( ', ' ) || 'none' } ). See lib/${ RN_IMPORT_SHIM_DIR } /README.md.`
132+ ` '${ chunk . name } ' (found: ${ required . join ( ', ' ) || 'none' } ). See lib/${ RN_IMPORT_SHIM_DIR } /README.md.`
118133 ) ;
119134 }
120135 }
0 commit comments