UNPKG

snyk-nodejs-lockfile-parser

Version:
59 lines 2.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNpmLockfileVersion = exports.getYarnLockfileVersion = exports.getLockfileVersionFromFile = exports.NodeLockfileVersion = void 0; const fs_1 = require("fs"); const errors_1 = require("./errors"); var NodeLockfileVersion; (function (NodeLockfileVersion) { NodeLockfileVersion["NpmLockV1"] = "NPM_LOCK_V1"; NodeLockfileVersion["NpmLockV2"] = "NPM_LOCK_V2"; NodeLockfileVersion["NpmLockV3"] = "NPM_LOCK_V3"; NodeLockfileVersion["YarnLockV1"] = "YARN_LOCK_V1"; NodeLockfileVersion["YarnLockV2"] = "YARN_LOCK_V2"; })(NodeLockfileVersion = exports.NodeLockfileVersion || (exports.NodeLockfileVersion = {})); const getLockfileVersionFromFile = (targetFile) => { const lockFileContents = (0, fs_1.readFileSync)(targetFile, 'utf-8'); if (targetFile.endsWith('package-lock.json')) { return getNpmLockfileVersion(lockFileContents); } else if (targetFile.endsWith('yarn.lock')) { return getYarnLockfileVersion(lockFileContents); } else { throw new errors_1.InvalidUserInputError(`Unknown lockfile ${targetFile}. ` + 'Please provide either package-lock.json or yarn.lock.'); } }; exports.getLockfileVersionFromFile = getLockfileVersionFromFile; function getYarnLockfileVersion(lockFileContents) { if (lockFileContents.includes('__metadata')) { return NodeLockfileVersion.YarnLockV2; } else { return NodeLockfileVersion.YarnLockV1; } } exports.getYarnLockfileVersion = getYarnLockfileVersion; function getNpmLockfileVersion(lockFileContents) { try { const lockfileJson = JSON.parse(lockFileContents); const lockfileVersion = lockfileJson.lockfileVersion || null; switch (lockfileVersion) { case null: case 1: return NodeLockfileVersion.NpmLockV1; case 2: return NodeLockfileVersion.NpmLockV2; case 3: return NodeLockfileVersion.NpmLockV3; default: throw new errors_1.InvalidUserInputError(`Unsupported npm lockfile version in package-lock.json. ` + 'Please provide a package-lock.json with lockfileVersion 1, 2 or 3'); } } catch (e) { throw new errors_1.InvalidUserInputError(`Problem parsing package-lock.json - make sure the package-lock.json is a valid JSON file`); } } exports.getNpmLockfileVersion = getNpmLockfileVersion; //# sourceMappingURL=utils.js.map