Skip to content

Commit

Permalink
Merge pull request #251 from danionescu/fix-node-modules-dependencies
Browse files Browse the repository at this point in the history
fix: make sure all the dependencies are checked when flattening the d…
  • Loading branch information
floydspace authored Feb 1, 2022
2 parents 09f08c7 + 0716acf commit 573385c
Showing 1 changed file with 42 additions and 5 deletions.
47 changes: 42 additions & 5 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,59 @@ export function extractFileNames(
});
}

/**
* Creates a "registry" of all the dependencies of the packages found in the tree described by deps.
* @param deps
*/
const buildAllDeps = (deps?: JSONObject) => {
if (!deps) {
return {};
}

const dependenciesLeft = Object.entries(deps);
const allDeps = {};

while (dependenciesLeft.length > 0) {
const [depName, details] = dependenciesLeft.shift();

if (
// we already have the dependencies for this package
depName in allDeps &&
'dependencies' in allDeps[depName]
) {
continue;
}

const dependencies = (details as JSONObject).dependencies;
if (dependencies) {
Object.entries(dependencies).forEach((dep) => dependenciesLeft.push(dep));
}

allDeps[depName] = allDeps[depName] || {};
allDeps[depName][(details as JSONObject).version] = details;
}

return allDeps;
};

/**
* Takes a dependency graph and returns a flat list of required production dependencies for all or the filtered deps
* @param deps A nested object as given by the `npm list --json` command
* @param filter an array of top dependencies to whitelist (takes all dependencies if omitted)
* @param allDeps an object containing the dependencies for each package, the keys being the package names
*/
export const flatDep = (deps: JSONObject, filter?: string[], originalObject?: JSONObject) => {
export const flatDep = (deps: JSONObject, filter?: string[], allDeps?: JSONObject) => {
if (!deps) return [];

// keep tracks of the original list when nested
if (!originalObject) originalObject = deps;
// keep tracks of all the dependencies for all the packages
if (!allDeps) allDeps = buildAllDeps(deps);

return Object.entries(deps).reduce((acc, [depName, details]) => {
if (filter && !filter.includes(depName)) return acc;
const detailsDeps =
originalObject[depName]?.dependencies || (details as JSONObject).dependencies;
return uniq([...acc, depName, ...flatDep(detailsDeps, undefined, originalObject)]);
allDeps[depName]?.[(details as JSONObject).version]?.dependencies ||
(details as JSONObject).dependencies;
return uniq([...acc, depName, ...flatDep(detailsDeps, undefined, allDeps)]);
}, []);
};

Expand Down

0 comments on commit 573385c

Please sign in to comment.