UNPKG

@snyk/dep-graph

Version:

Snyk dependency graph library

77 lines 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SUPPORTED_SCHEMA_RANGE = void 0; exports.createFromJSON = createFromJSON; const semver = require("semver"); const graphlib = require("../graphlib"); const errors_1 = require("./errors"); const validate_graph_1 = require("./validate-graph"); const dep_graph_1 = require("./dep-graph"); exports.SUPPORTED_SCHEMA_RANGE = '^1.0.0'; /** * Create a DepGraph instance from a JSON representation of a dep graph. This * is typically used after passing the graph over the wire as `DepGraphData`. */ function createFromJSON(depGraphData, shouldValidate = true) { if (shouldValidate) { assertValidSchema(depGraphData); } const graph = new graphlib.Graph({ directed: true, multigraph: false, compound: false, }); const pkgs = {}; const pkgNodes = {}; for (const { id, info } of depGraphData.pkgs) { if (shouldValidate) { assertValidPkg(id, info, pkgs); } pkgs[id] = info.version ? info : { ...info, version: undefined }; } const rootNodeId = depGraphData.graph.rootNodeId; let rootNode; for (const node of depGraphData.graph.nodes) { if (shouldValidate) { assert(!graph.hasNode(node.nodeId), 'more than one node with same id'); assert(!!pkgs[node.pkgId], 'some instance nodes belong to non-existing pkgIds'); } if (node.nodeId === rootNodeId) rootNode = node; const pkgId = node.pkgId; if (!pkgNodes[pkgId]) { pkgNodes[pkgId] = new Set(); } pkgNodes[pkgId].add(node.nodeId); graph.setNode(node.nodeId, { pkgId, info: node.info }); } for (const node of depGraphData.graph.nodes) { for (const depNodeId of node.deps) { graph.setEdge(node.nodeId, depNodeId.nodeId); } } if (shouldValidate) { assert(!!rootNode, `.${rootNodeId} root graph node is missing`); const rootPkgId = rootNode.pkgId; assert(!!pkgs[rootPkgId], `.${rootPkgId} root pkg missing`); (0, validate_graph_1.validateGraph)(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes); } return new dep_graph_1.DepGraphImpl(graph, depGraphData.graph.rootNodeId, pkgs, pkgNodes, depGraphData.pkgManager); } function assert(condition, msg) { if (!condition) { throw new errors_1.ValidationError(msg); } } function assertValidSchema({ schemaVersion, pkgManager }) { assert(!!semver.valid(schemaVersion) && semver.satisfies(schemaVersion, exports.SUPPORTED_SCHEMA_RANGE), `dep-graph schemaVersion not in "${exports.SUPPORTED_SCHEMA_RANGE}"`); assert(pkgManager && !!pkgManager.name, '.pkgManager.name is missing'); } function assertValidPkg(id, info, pkgs) { assert(!pkgs[id], 'more than one pkg with same id'); assert(!!info, '.pkgs item missing .info'); assert(id === dep_graph_1.DepGraphImpl.getPkgId(info), 'pkgs ids should be name@version'); assert(!!info.name, 'some .pkgs elements have no .name field'); } //# sourceMappingURL=create-from-json.js.map