Skip to content

Commit

Permalink
Warn when importing modules within other entry points.
Browse files Browse the repository at this point in the history
It would be nice to make this an error that would fail the build, but
there are a couple of benign violations that would be disruptive to fix at
this point, like reexporting `../ApolloClient` from `./core/QueryManager`,
and `./testing/index.ts` reaching into `../utilities/testing`.
  • Loading branch information
benjamn committed Jul 20, 2020
1 parent 8aa5826 commit f634785
Showing 1 changed file with 53 additions and 11 deletions.
64 changes: 53 additions & 11 deletions config/entryPoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,63 @@ const path = require("path").posix;

exports.check = function (id, parentId) {
const resolved = path.resolve(path.dirname(parentId), id);
const resolvedParts = resolved.split(path.sep);
const distIndex = resolvedParts.lastIndexOf("dist");
const importedParts = partsAfterDist(resolved);

if (distIndex >= 0) {
let node = lookupTrie;

for (let i = distIndex + 1;
node && i < resolvedParts.length;
++i) {
const dir = resolvedParts[i];
node = node && node.dirs && node.dirs[dir];
if (importedParts) {
const entryPointIndex = lengthOfLongestEntryPoint(importedParts);
if (entryPointIndex === importedParts.length) {
return true;
}

return Boolean(node && node.isEntry);
if (entryPointIndex >= 0) {
const parentParts = partsAfterDist(parentId);
const parentEntryPointIndex = lengthOfLongestEntryPoint(parentParts);
const sameEntryPoint =
entryPointIndex === parentEntryPointIndex &&
arraysEqualUpTo(importedParts, parentParts, entryPointIndex);

// If the imported ID and the parent ID have the same longest entry
// point prefix, then this import is safely confined within that
// entry point. Returning false lets Rollup know this import is not
// external, and can be bundled into the CJS bundle that we build
// for this shared entry point.
if (sameEntryPoint) {
return false;
}

console.warn(`Risky cross-entry-point nested import of ${id} in ${
partsAfterDist(parentId).join("/")
}`);
}
}

return false;
};

function partsAfterDist(id) {
const parts = id.split(path.sep);
const distIndex = parts.lastIndexOf("dist");
if (distIndex >= 0) {
return parts.slice(distIndex + 1);
}
}

function lengthOfLongestEntryPoint(parts) {
let node = lookupTrie;
let longest = -1;
for (let i = 0; node && i < parts.length; ++i) {
if (node.isEntry) longest = i;
node = node.dirs && node.dirs[parts[i]];
}
if (node && node.isEntry) {
return parts.length;
}
return longest;
}

function arraysEqualUpTo(a, b, end) {
for (let i = 0; i < end; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}

0 comments on commit f634785

Please sign in to comment.