"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildDepGraphPnpm = void 0;
const dep_graph_1 = require("@snyk/dep-graph");
const util_1 = require("../util");
const utils_1 = require("./utils");
const event_loop_spinner_1 = require("event-loop-spinner");
const error_catalog_nodejs_public_1 = require("@snyk/error-catalog-nodejs-public");
const out_of_sync_error_1 = require("../../errors/out-of-sync-error");
const __1 = require("../..");
const debugModule = require("debug");
const constants_1 = require("./constants");
const debug = debugModule('snyk-pnpm-workspaces');
const buildDepGraphPnpm = async (lockFileParser, pkgJson, options, importer) => {
    var _a;
    const { strictOutOfSync, includeOptionalDeps, includeDevDeps, pruneWithinTopLevelDeps, } = options;
    const depGraphBuilder = new dep_graph_1.DepGraphBuilder({ name: 'pnpm' }, { name: pkgJson.name, version: pkgJson.version || constants_1.UNDEFINED_VERSION });
    lockFileParser.extractedPackages = lockFileParser.extractPackages();
    const extractedPnpmPkgs = lockFileParser.extractedPackages;
    const topLevelDeps = (0, util_1.getTopLevelDeps)(pkgJson, options);
    const extractedTopLevelDeps = lockFileParser.extractTopLevelDependencies(options, importer) || {};
    for (const name of Object.keys(topLevelDeps)) {
        if (!extractedTopLevelDeps[name]) {
            if (!strictOutOfSync) {
                continue;
            }
            const errMessage = `Dependency ${name} was not found in ` +
                `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]}. Your package.json and ` +
                `${out_of_sync_error_1.LOCK_FILE_NAME[__1.LockfileType.pnpm]} are probably out of sync. Please run ` +
                `"${out_of_sync_error_1.INSTALL_COMMAND[__1.LockfileType.pnpm]}" and try again.`;
            debug(errMessage);
            throw new error_catalog_nodejs_public_1.OpenSourceEcosystems.PnpmOutOfSyncError(errMessage);
        }
        topLevelDeps[name].version = extractedTopLevelDeps[name].version;
    }
    const rootNode = {
        id: 'root-node',
        name: pkgJson.name,
        version: pkgJson.version,
        dependencies: topLevelDeps,
        isDev: false,
    };
    const rootNodeId = `${pkgJson.name}@${pkgJson.version}`;
    await dfsVisit(depGraphBuilder, rootNodeId, rootNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, ((_a = pkgJson.pnpm) === null || _a === void 0 ? void 0 : _a.overrides) || {}, pruneWithinTopLevelDeps, lockFileParser);
    return depGraphBuilder.build();
};
exports.buildDepGraphPnpm = buildDepGraphPnpm;
/**
 * Use DFS to add all nodes and edges to the depGraphBuilder and prune cyclic nodes.
 * The visitedMap keep track of which nodes have already been discovered during traversal.
 *  - If a node doesn't exist in the map, it means it hasn't been visited.
 *  - If a node is already visited, simply connect the new node with this node.
 */
const dfsVisit = async (depGraphBuilder, rootNodeId, node, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, visited) => {
    for (const [name, depInfo] of Object.entries(node.dependencies || {})) {
        if (event_loop_spinner_1.eventLoopSpinner.isStarving()) {
            await event_loop_spinner_1.eventLoopSpinner.spin();
        }
        const localVisited = visited || new Set();
        const childNode = (0, utils_1.getPnpmChildNode)(name, depInfo, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, lockFileParser);
        if (localVisited.has(childNode.id) || childNode.id == rootNodeId) {
            if (pruneWithinTopLevel) {
                const prunedId = `${childNode.id}:pruned`;
                depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, prunedId, {
                    labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod', pruned: 'true' }, (node.missingLockFileEntry && {
                        missingLockFileEntry: 'true',
                    })),
                });
                depGraphBuilder.connectDep(node.id, prunedId);
            }
            else {
                depGraphBuilder.connectDep(node.id, childNode.id);
            }
            continue;
        }
        depGraphBuilder.addPkgNode({ name: childNode.name, version: childNode.version }, childNode.id, {
            labels: Object.assign({ scope: childNode.isDev ? 'dev' : 'prod' }, (node.missingLockFileEntry && {
                missingLockFileEntry: 'true',
            })),
        });
        depGraphBuilder.connectDep(node.id, childNode.id);
        localVisited.add(childNode.id);
        await dfsVisit(depGraphBuilder, rootNodeId, childNode, extractedPnpmPkgs, strictOutOfSync, includeOptionalDeps, includeDevDeps, overrides, pruneWithinTopLevel, lockFileParser, localVisited);
    }
};
//# sourceMappingURL=build-dep-graph-pnpm.js.map