"use strict";
exports.id = 959;
exports.ids = [959];
exports.modules = {

/***/ 61900:
/***/ ((__unused_webpack_module, exports) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.countTotalDependenciesInTree = void 0;
function countTotalDependenciesInTree(depTree) {
    let count = 0;
    if (depTree.dependencies) {
        for (const name of Object.keys(depTree.dependencies)) {
            const dep = depTree.dependencies[name];
            if (dep) {
                count += 1 + countTotalDependenciesInTree(dep);
            }
        }
    }
    return count;
}
exports.countTotalDependenciesInTree = countTotalDependenciesInTree;


/***/ }),

/***/ 55916:
/***/ ((__unused_webpack_module, exports) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.dropEmptyDeps = void 0;
function dropEmptyDeps(depTree) {
    if (depTree.dependencies) {
        const keys = Object.keys(depTree.dependencies);
        if (keys.length === 0) {
            delete depTree.dependencies;
        }
        else {
            for (const k of keys) {
                dropEmptyDeps(depTree.dependencies[k]);
            }
        }
    }
    return depTree;
}
exports.dropEmptyDeps = dropEmptyDeps;


/***/ }),

/***/ 85768:
/***/ ((__unused_webpack_module, exports) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.filterOutMissingDeps = void 0;
function filterOutMissingDeps(depTree) {
    const filteredDeps = {};
    const missingDeps = [];
    if (!depTree.dependencies) {
        return {
            filteredDepTree: depTree,
            missingDeps,
        };
    }
    for (const depKey of Object.keys(depTree.dependencies)) {
        const dep = depTree.dependencies[depKey];
        if (dep.missingLockFileEntry ||
            (dep.labels && dep.labels.missingLockFileEntry)) {
            // TODO(kyegupov): add field to the type
            missingDeps.push(`${dep.name}@${dep.version}`);
        }
        else {
            filteredDeps[depKey] = dep;
        }
    }
    const filteredDepTree = {
        ...depTree,
        dependencies: filteredDeps,
    };
    return {
        filteredDepTree,
        missingDeps,
    };
}
exports.filterOutMissingDeps = filterOutMissingDeps;


/***/ }),

/***/ 3959:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.monitorDepGraph = exports.monitor = void 0;
const Debug = __webpack_require__(15158);
const path = __webpack_require__(85622);
const depGraphLib = __webpack_require__(71479);
const snyk = __webpack_require__(9146);
const api_token_1 = __webpack_require__(95181);
const request_1 = __webpack_require__(52050);
const config = __webpack_require__(22541);
const os = __webpack_require__(12087);
const get = __webpack_require__(29208);
const camelCase = __webpack_require__(76884);
const is_ci_1 = __webpack_require__(10090);
const analytics = __webpack_require__(82744);
const projectMetadata = __webpack_require__(3594);
const errors_1 = __webpack_require__(55191);
const prune_1 = __webpack_require__(87725);
const package_managers_1 = __webpack_require__(53847);
const feature_flags_1 = __webpack_require__(82426);
const count_total_deps_in_tree_1 = __webpack_require__(61900);
const filter_out_missing_deps_1 = __webpack_require__(85768);
const drop_empty_deps_1 = __webpack_require__(55916);
const prune_dep_tree_1 = __webpack_require__(35797);
const policy_1 = __webpack_require__(32615);
const types_1 = __webpack_require__(39409);
const reachable_vulns_1 = __webpack_require__(86978);
const utils_1 = __webpack_require__(49530);
const utils_2 = __webpack_require__(61721);
const alerts = __webpack_require__(21696);
const error_format_1 = __webpack_require__(59369);
const debug = Debug('snyk');
const ANALYTICS_PAYLOAD_MAX_LENGTH = 1024;
async function monitor(root, meta, scannedProject, options, pluginMeta, targetFileRelativePath, contributors) {
    api_token_1.apiOrOAuthTokenExists();
    const packageManager = meta.packageManager;
    analytics.add('packageManager', packageManager);
    analytics.add('isDocker', !!meta.isDocker);
    if (scannedProject.depGraph) {
        return await monitorDepGraph(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors);
    }
    // TODO @boost: delete this once 'experimental-dep-graph' ff is deleted
    if (package_managers_1.GRAPH_SUPPORTED_PACKAGE_MANAGERS.includes(packageManager)) {
        const monitorGraphSupportedRes = await feature_flags_1.isFeatureFlagSupportedForOrg(camelCase('experimental-dep-graph'), options.org || config.org);
        if (monitorGraphSupportedRes.code === 401) {
            throw errors_1.AuthFailedError(monitorGraphSupportedRes.error, monitorGraphSupportedRes.code);
        }
        if (monitorGraphSupportedRes.ok) {
            return await experimentalMonitorDepGraphFromDepTree(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors);
        }
        if (monitorGraphSupportedRes.userMessage) {
            debug(monitorGraphSupportedRes.userMessage);
        }
    }
    return await monitorDepTree(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors);
}
exports.monitor = monitor;
async function monitorDepTree(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors) {
    var _a;
    let treeMissingDeps = [];
    const packageManager = meta.packageManager;
    let depTree = scannedProject.depTree;
    if (!depTree) {
        debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
        throw new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io');
    }
    let prePruneDepCount;
    if (meta.prune) {
        debug('prune used, counting total dependencies');
        prePruneDepCount = count_total_deps_in_tree_1.countTotalDependenciesInTree(depTree);
        analytics.add('prePruneDepCount', prePruneDepCount);
        debug('total dependencies: %d', prePruneDepCount);
        debug('pruning dep tree');
        depTree = await prune_dep_tree_1.pruneTree(depTree, meta.packageManager);
        debug('finished pruning dep tree');
    }
    if (['npm', 'yarn'].includes(meta.packageManager)) {
        const { filteredDepTree, missingDeps } = filter_out_missing_deps_1.filterOutMissingDeps(depTree);
        depTree = filteredDepTree;
        treeMissingDeps = missingDeps;
    }
    let targetFileDir;
    if (targetFileRelativePath) {
        const { dir } = path.parse(targetFileRelativePath);
        targetFileDir = dir;
    }
    const policy = await policy_1.findAndLoadPolicy(root, meta.isDocker ? 'docker' : packageManager, options, 
    // TODO: fix this and send only send when we used resolve-deps for node
    // it should be a ExpandedPkgTree type instead
    depTree, targetFileDir);
    const target = await projectMetadata.getInfo(scannedProject, meta, depTree);
    if (types_1.isGitTarget(target) && target.branch) {
        analytics.add('targetBranch', target.branch);
    }
    depTree = drop_empty_deps_1.dropEmptyDeps(depTree);
    let callGraphPayload;
    if (options.reachableVulns && ((_a = scannedProject.callGraph) === null || _a === void 0 ? void 0 : _a.innerError)) {
        const err = scannedProject.callGraph;
        analytics.add('callGraphError', error_format_1.abridgeErrorMessage(err.innerError.toString(), ANALYTICS_PAYLOAD_MAX_LENGTH));
        alerts.registerAlerts([
            {
                type: 'error',
                name: 'missing-call-graph',
                msg: err.message,
            },
        ]);
    }
    else if (scannedProject.callGraph) {
        const { callGraph, nodeCount, edgeCount } = reachable_vulns_1.serializeCallGraphWithMetrics(scannedProject.callGraph);
        debug(`Adding call graph to payload, node count: ${nodeCount}, edge count: ${edgeCount}`);
        const callGraphMetrics = get(pluginMeta, 'meta.callGraphMetrics', {});
        analytics.add('callGraphMetrics', {
            callGraphEdgeCount: edgeCount,
            callGraphNodeCount: nodeCount,
            ...callGraphMetrics,
        });
        callGraphPayload = callGraph;
    }
    // TODO(kyegupov): async/await
    return new Promise((resolve, reject) => {
        var _a, _b, _c;
        if (!depTree) {
            debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
            return reject(new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io'));
        }
        request_1.makeRequest({
            body: {
                meta: {
                    method: meta.method,
                    hostname: os.hostname(),
                    id: snyk.id || depTree.name,
                    ci: is_ci_1.isCI(),
                    pid: process.pid,
                    node: process.version,
                    master: snyk.config.isMaster,
                    name: utils_1.getNameDepTree(scannedProject, depTree, meta),
                    version: depTree.version,
                    org: config.org ? decodeURIComponent(config.org) : undefined,
                    pluginName: pluginMeta.name,
                    pluginRuntime: pluginMeta.runtime,
                    missingDeps: treeMissingDeps,
                    dockerImageId: pluginMeta.dockerImageId,
                    dockerBaseImage: depTree.docker
                        ? depTree.docker.baseImage
                        : undefined,
                    dockerfileLayers: depTree.docker
                        ? depTree.docker.dockerfileLayers
                        : undefined,
                    projectName: utils_1.getProjectName(scannedProject, meta),
                    prePruneDepCount,
                    monitorGraph: false,
                    versionBuildInfo: JSON.stringify((_a = scannedProject.meta) === null || _a === void 0 ? void 0 : _a.versionBuildInfo),
                    gradleProjectName: (_b = scannedProject.meta) === null || _b === void 0 ? void 0 : _b.gradleProjectName,
                    platform: (_c = scannedProject.meta) === null || _c === void 0 ? void 0 : _c.platform,
                },
                policy: policy ? policy.toString() : undefined,
                package: depTree,
                callGraph: callGraphPayload,
                // we take the targetFile from the plugin,
                // because we want to send it only for specific package-managers
                target,
                // WARNING: be careful changing this as it affects project uniqueness
                targetFile: utils_1.getTargetFile(scannedProject, pluginMeta),
                targetFileRelativePath,
                contributors,
            },
            gzip: true,
            method: 'PUT',
            headers: {
                authorization: api_token_1.getAuthHeader(),
                'content-encoding': 'gzip',
            },
            url: config.API + '/monitor/' + packageManager,
            json: true,
        }, (error, res, body) => {
            if (error) {
                return reject(error);
            }
            if (res.statusCode >= 200 && res.statusCode <= 299) {
                resolve(body);
            }
            else {
                let err;
                const userMessage = body && body.userMessage;
                if (!userMessage && res.statusCode === 504) {
                    err = new errors_1.ConnectionTimeoutError();
                }
                else {
                    err = new errors_1.MonitorError(res.statusCode, userMessage);
                }
                reject(err);
            }
        });
    });
}
async function monitorDepGraph(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors) {
    var _a;
    const packageManager = meta.packageManager;
    analytics.add('monitorDepGraph', true);
    let depGraph = scannedProject.depGraph;
    if (!depGraph) {
        debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
        throw new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io');
    }
    let targetFileDir;
    if (targetFileRelativePath) {
        const { dir } = path.parse(targetFileRelativePath);
        targetFileDir = dir;
    }
    const policy = await policy_1.findAndLoadPolicy(root, meta.isDocker ? 'docker' : packageManager, options, undefined, targetFileDir);
    const target = await projectMetadata.getInfo(scannedProject, meta);
    if (types_1.isGitTarget(target) && target.branch) {
        analytics.add('targetBranch', target.branch);
    }
    const pruneIsRequired = options.pruneRepeatedSubdependencies;
    depGraph = await prune_1.pruneGraph(depGraph, packageManager, pruneIsRequired);
    let callGraphPayload;
    if (options.reachableVulns && ((_a = scannedProject.callGraph) === null || _a === void 0 ? void 0 : _a.innerError)) {
        const err = scannedProject.callGraph;
        analytics.add('callGraphError', error_format_1.abridgeErrorMessage(err.innerError.toString(), ANALYTICS_PAYLOAD_MAX_LENGTH));
        alerts.registerAlerts([
            {
                type: 'error',
                name: 'missing-call-graph',
                msg: err.message,
            },
        ]);
    }
    else if (scannedProject.callGraph) {
        const { callGraph, nodeCount, edgeCount } = reachable_vulns_1.serializeCallGraphWithMetrics(scannedProject.callGraph);
        debug(`Adding call graph to payload, node count: ${nodeCount}, edge count: ${edgeCount}`);
        const callGraphMetrics = get(pluginMeta, 'meta.callGraphMetrics', {});
        analytics.add('callGraphMetrics', {
            callGraphEdgeCount: edgeCount,
            callGraphNodeCount: nodeCount,
            ...callGraphMetrics,
        });
        callGraphPayload = callGraph;
    }
    return new Promise((resolve, reject) => {
        var _a, _b;
        if (!depGraph) {
            debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
            return reject(new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io'));
        }
        request_1.makeRequest({
            body: {
                meta: {
                    method: meta.method,
                    hostname: os.hostname(),
                    id: snyk.id || depGraph.rootPkg.name,
                    ci: is_ci_1.isCI(),
                    pid: process.pid,
                    node: process.version,
                    master: snyk.config.isMaster,
                    name: utils_1.getNameDepGraph(scannedProject, depGraph, meta),
                    version: depGraph.rootPkg.version,
                    org: config.org ? decodeURIComponent(config.org) : undefined,
                    pluginName: pluginMeta.name,
                    pluginRuntime: pluginMeta.runtime,
                    projectName: utils_1.getProjectName(scannedProject, meta),
                    monitorGraph: true,
                    versionBuildInfo: JSON.stringify((_a = scannedProject.meta) === null || _a === void 0 ? void 0 : _a.versionBuildInfo),
                    gradleProjectName: (_b = scannedProject.meta) === null || _b === void 0 ? void 0 : _b.gradleProjectName,
                },
                policy: policy ? policy.toString() : undefined,
                depGraphJSON: depGraph,
                // we take the targetFile from the plugin,
                // because we want to send it only for specific package-managers
                target,
                targetFile: utils_1.getTargetFile(scannedProject, pluginMeta),
                targetFileRelativePath,
                contributors,
                callGraph: callGraphPayload,
            },
            gzip: true,
            method: 'PUT',
            headers: {
                authorization: api_token_1.getAuthHeader(),
                'content-encoding': 'gzip',
            },
            url: `${config.API}/monitor/${packageManager}/graph`,
            json: true,
        }, (error, res, body) => {
            if (error) {
                return reject(error);
            }
            if (res.statusCode >= 200 && res.statusCode <= 299) {
                resolve(body);
            }
            else {
                let err;
                const userMessage = body && body.userMessage;
                if (!userMessage && res.statusCode === 504) {
                    err = new errors_1.ConnectionTimeoutError();
                }
                else {
                    err = new errors_1.MonitorError(res.statusCode, userMessage);
                }
                reject(err);
            }
        });
    });
}
exports.monitorDepGraph = monitorDepGraph;
/**
 * @deprecated it will be deleted once experimentalDepGraph FF will be deleted
 * and npm, yarn, sbt and rubygems usage of `experimentalMonitorDepGraphFromDepTree`
 * will be replaced with `monitorDepGraph` method
 */
async function experimentalMonitorDepGraphFromDepTree(root, meta, scannedProject, pluginMeta, options, targetFileRelativePath, contributors) {
    const packageManager = meta.packageManager;
    analytics.add('experimentalMonitorDepGraphFromDepTree', true);
    let treeMissingDeps;
    let depTree = scannedProject.depTree;
    if (!depTree) {
        debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
        throw new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io');
    }
    let targetFileDir;
    if (targetFileRelativePath) {
        const { dir } = path.parse(targetFileRelativePath);
        targetFileDir = dir;
    }
    const policy = await policy_1.findAndLoadPolicy(root, meta.isDocker ? 'docker' : packageManager, options, 
    // TODO: fix this and send only send when we used resolve-deps for node
    // it should be a ExpandedPkgTree type instead
    depTree, targetFileDir);
    if (['npm', 'yarn'].includes(meta.packageManager)) {
        const { filteredDepTree, missingDeps } = filter_out_missing_deps_1.filterOutMissingDeps(depTree);
        depTree = filteredDepTree;
        treeMissingDeps = missingDeps;
    }
    const depGraph = await depGraphLib.legacy.depTreeToGraph(depTree, packageManager);
    const target = await projectMetadata.getInfo(scannedProject, meta, depTree);
    if (types_1.isGitTarget(target) && target.branch) {
        analytics.add('targetBranch', target.branch);
    }
    let prunedGraph = depGraph;
    let prePruneDepCount;
    if (meta.prune) {
        debug('Trying to prune the graph');
        prePruneDepCount = utils_2.countPathsToGraphRoot(depGraph);
        debug('pre prunedPathsCount: ' + prePruneDepCount);
        prunedGraph = await prune_1.pruneGraph(depGraph, packageManager, meta.prune);
    }
    return new Promise((resolve, reject) => {
        if (!depTree) {
            debug('scannedProject is missing depGraph or depTree, cannot run test/monitor');
            return reject(new errors_1.FailedToRunTestError('Your monitor request could not be completed. Please email support@snyk.io'));
        }
        request_1.makeRequest({
            body: {
                meta: {
                    method: meta.method,
                    hostname: os.hostname(),
                    id: snyk.id || depTree.name,
                    ci: is_ci_1.isCI(),
                    pid: process.pid,
                    node: process.version,
                    master: snyk.config.isMaster,
                    name: utils_1.getNameDepGraph(scannedProject, depGraph, meta),
                    version: depGraph.rootPkg.version,
                    org: config.org ? decodeURIComponent(config.org) : undefined,
                    pluginName: pluginMeta.name,
                    pluginRuntime: pluginMeta.runtime,
                    dockerImageId: pluginMeta.dockerImageId,
                    dockerBaseImage: depTree.docker
                        ? depTree.docker.baseImage
                        : undefined,
                    dockerfileLayers: depTree.docker
                        ? depTree.docker.dockerfileLayers
                        : undefined,
                    projectName: utils_1.getProjectName(scannedProject, meta),
                    prePruneDepCount,
                    missingDeps: treeMissingDeps,
                    monitorGraph: true,
                },
                policy: policy ? policy.toString() : undefined,
                depGraphJSON: prunedGraph,
                // we take the targetFile from the plugin,
                // because we want to send it only for specific package-managers
                target,
                targetFile: utils_1.getTargetFile(scannedProject, pluginMeta),
                targetFileRelativePath,
                contributors,
            },
            gzip: true,
            method: 'PUT',
            headers: {
                authorization: api_token_1.getAuthHeader(),
                'content-encoding': 'gzip',
            },
            url: `${config.API}/monitor/${packageManager}/graph`,
            json: true,
        }, (error, res, body) => {
            if (error) {
                return reject(error);
            }
            if (res.statusCode >= 200 && res.statusCode <= 299) {
                resolve(body);
            }
            else {
                let err;
                const userMessage = body && body.userMessage;
                if (!userMessage && res.statusCode === 504) {
                    err = new errors_1.ConnectionTimeoutError();
                }
                else {
                    err = new errors_1.MonitorError(res.statusCode, userMessage);
                }
                reject(err);
            }
        });
    });
}


/***/ }),

/***/ 35797:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pruneTree = void 0;
const depGraphLib = __webpack_require__(71479);
async function pruneTree(tree, packageManagerName) {
    // Pruning requires conversion to the graph first.
    // This is slow.
    const graph = await depGraphLib.legacy.depTreeToGraph(tree, packageManagerName);
    const prunedTree = (await depGraphLib.legacy.graphToDepTree(graph, packageManagerName, { deduplicateWithinTopLevelDeps: true }));
    // Transplant pruned dependencies in the original tree (we want to keep all other fields):
    tree.dependencies = prunedTree.dependencies;
    return tree;
}
exports.pruneTree = pruneTree;


/***/ }),

/***/ 49530:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getTargetFile = exports.getProjectName = exports.getNameDepGraph = exports.getNameDepTree = void 0;
const container_1 = __webpack_require__(51804);
function getNameDepTree(scannedProject, depTree, meta) {
    if (container_1.isContainer(scannedProject)) {
        return container_1.getContainerName(scannedProject, meta);
    }
    return depTree.name;
}
exports.getNameDepTree = getNameDepTree;
function getNameDepGraph(scannedProject, depGraph, meta) {
    var _a;
    if (container_1.isContainer(scannedProject)) {
        return container_1.getContainerName(scannedProject, meta);
    }
    return (_a = depGraph.rootPkg) === null || _a === void 0 ? void 0 : _a.name;
}
exports.getNameDepGraph = getNameDepGraph;
function getProjectName(scannedProject, meta) {
    var _a;
    if (container_1.isContainer(scannedProject)) {
        return container_1.getContainerProjectName(scannedProject, meta);
    }
    if (meta['project-name'] && ((_a = scannedProject.meta) === null || _a === void 0 ? void 0 : _a.projectName)) {
        return scannedProject.meta.projectName;
    }
    return meta['project-name'];
}
exports.getProjectName = getProjectName;
function getTargetFile(scannedProject, pluginMeta) {
    if (container_1.isContainer(scannedProject)) {
        return container_1.getContainerTargetFile(scannedProject);
    }
    return pluginMeta.targetFile;
}
exports.getTargetFile = getTargetFile;


/***/ }),

/***/ 39409:
/***/ ((__unused_webpack_module, exports) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isGitTarget = void 0;
function isGitTarget(target) {
    return target && (target.branch || target.remoteUrl);
}
exports.isGitTarget = isGitTarget;


/***/ })

};
;
//# sourceMappingURL=959.index.js.map