-
Notifications
You must be signed in to change notification settings - Fork 915
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve named export analysis #1649
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,11 @@ | ||
import * as colors from 'kleur/colors'; | ||
import path from 'path'; | ||
import fs from 'fs'; | ||
import {VM as VM2} from 'vm2'; | ||
import {Plugin} from 'rollup'; | ||
import {InstallTarget, AbstractLogger} from '../types'; | ||
import {getWebDependencyName} from '../util.js'; | ||
import {getWebDependencyName, isTruthy} from '../util.js'; | ||
// Use CJS intentionally here! ESM interface is async but CJS is sync, and this file is sync | ||
const {parse} = require('cjs-module-lexer'); | ||
|
||
/** | ||
|
@@ -30,8 +32,9 @@ export function rollupPluginWrapInstallTargets( | |
/** | ||
* Runtime analysis: High Fidelity, but not always successful. | ||
* `require()` the CJS file inside of Node.js to load the package and detect it's runtime exports. | ||
* TODO: Safe to remove now that cjsAutoDetectExportsUntrusted() is getting smarter? | ||
*/ | ||
function cjsAutoDetectExportsRuntime(normalizedFileLoc: string): string[] | undefined { | ||
function cjsAutoDetectExportsTrusted(normalizedFileLoc: string): string[] | undefined { | ||
try { | ||
const mod = require(normalizedFileLoc); | ||
// skip analysis for non-object modules, these can only be the default export. | ||
|
@@ -54,7 +57,11 @@ export function rollupPluginWrapInstallTargets( | |
* Get the exports that we scanned originally using static analysis. This is meant to run on | ||
* any file (not only CJS) but it will only return an array if CJS exports were found. | ||
*/ | ||
function cjsAutoDetectExportsStatic(filename: string, visited = new Set()): string[] | undefined { | ||
function cjsAutoDetectExportsUntrusted( | ||
filename: string, | ||
visited = new Set(), | ||
): string[] | undefined { | ||
const isMainEntrypoint = visited.size === 0; | ||
// Prevent infinite loops via circular dependencies. | ||
if (visited.has(filename)) { | ||
return []; | ||
|
@@ -63,16 +70,42 @@ export function rollupPluginWrapInstallTargets( | |
} | ||
const fileContents = fs.readFileSync(filename, 'utf-8'); | ||
try { | ||
const {exports, reexports} = parse(fileContents); | ||
const resolvedReexports = reexports.map((e) => | ||
cjsAutoDetectExportsStatic(require.resolve(e, {paths: [path.dirname(filename)]}), visited), | ||
); | ||
// Attempt 1 - CJS: Run cjs-module-lexer to statically analyze exports. | ||
let {exports, reexports} = parse(fileContents); | ||
// If re-exports were detected (`exports.foo = require(...)`) then resolve them here. | ||
let resolvedReexports: string[] = []; | ||
if (reexports.length > 0) { | ||
resolvedReexports = ([] as string[]).concat.apply( | ||
[], | ||
reexports | ||
.map((e) => | ||
cjsAutoDetectExportsUntrusted( | ||
require.resolve(e, {paths: [path.dirname(filename)]}), | ||
visited, | ||
), | ||
) | ||
.filter(isTruthy), | ||
); | ||
} | ||
// Attempt 2 - UMD: Run the file in a sandbox to dynamically analyze exports. | ||
// This will only work on UMD and very simple CJS files (require not supported). | ||
// Uses VM2 to run safely sandbox untrusted code (no access no Node.js primitives, just JS). | ||
if (isMainEntrypoint && exports.length === 0 && reexports.length === 0) { | ||
const vm = new VM2({wasm: false, fixAsync: false}); | ||
exports = Object.keys( | ||
vm.run( | ||
'const exports={}; const module={exports}; ' + fileContents + ';; module.exports;', | ||
), | ||
); | ||
} | ||
|
||
// Resolve and flatten all exports into a single array, and remove invalid exports. | ||
return Array.from(new Set([...exports, ...resolvedReexports])).filter( | ||
(imp) => imp !== 'default' && imp !== '__esModule', | ||
); | ||
} catch (err) { | ||
// Safe to ignore, this is usually due to the file not being CJS. | ||
logger.debug(`cjsAutoDetectExportsStatic error: ${err.message}`); | ||
logger.debug(`cjsAutoDetectExportsUntrusted error: ${err.message}`); | ||
} | ||
} | ||
|
||
|
@@ -98,8 +131,8 @@ export function rollupPluginWrapInstallTargets( | |
normalizedFileLoc.includes(`node_modules/${p}${p.endsWith('.js') ? '' : '/'}`), | ||
); | ||
const cjsExports = isExplicitAutoDetect | ||
? cjsAutoDetectExportsRuntime(val) | ||
: cjsAutoDetectExportsStatic(val); | ||
? cjsAutoDetectExportsTrusted(val) | ||
: cjsAutoDetectExportsUntrusted(val); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. chose more appropriate names, now that there's a (sandboxed) runtime aspect to our untrusted scanner. |
||
if (cjsExports && cjsExports.length > 0) { | ||
cjsScannedNamedExports.set(normalizedFileLoc, cjsExports); | ||
input[key] = `snowpack-wrap:${val}`; | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what if module.exports isn't an object?
|| {}
?