|
| 1 | +import {readFile} from "node:fs/promises"; |
| 2 | +import path from "path"; |
| 3 | +import {Arborist} from "@npmcli/arborist"; |
| 4 | +import pacote from "pacote"; |
| 5 | + |
| 6 | +async function readJson(filePath) { |
| 7 | + const jsonString = await readFile(filePath, {encoding: "utf-8"}); |
| 8 | + return JSON.parse(jsonString); |
| 9 | +} |
| 10 | + |
| 11 | +export default async function convertPackageLockToShrinkwrap(workspaceRootDir, targetPackageName) { |
| 12 | + const packageLockJson = await readJson(path.join(workspaceRootDir, "package-lock.json")); |
| 13 | + |
| 14 | + // Input validation |
| 15 | + if (!packageLockJson || typeof packageLockJson !== "object") { |
| 16 | + throw new Error("Invalid package-lock.json: must be a valid JSON object"); |
| 17 | + } |
| 18 | + |
| 19 | + if (!targetPackageName || typeof targetPackageName !== "string" || targetPackageName.trim() === "") { |
| 20 | + throw new Error("Invalid target package name: must be a non-empty string"); |
| 21 | + } |
| 22 | + |
| 23 | + if (!packageLockJson.packages) { |
| 24 | + throw new Error("Invalid package-lock.json: missing packages field"); |
| 25 | + } |
| 26 | + |
| 27 | + if (typeof packageLockJson.packages !== "object") { |
| 28 | + throw new Error("Invalid package-lock.json: packages field must be an object"); |
| 29 | + } |
| 30 | + |
| 31 | + // Validate lockfile version - only support version 3 |
| 32 | + if (packageLockJson.lockfileVersion && packageLockJson.lockfileVersion !== 3) { |
| 33 | + throw new Error(`Unsupported lockfile version: ${packageLockJson.lockfileVersion}. Only lockfile version 3 is supported`); |
| 34 | + } |
| 35 | + |
| 36 | + // Default to version 3 if not specified |
| 37 | + if (!packageLockJson.lockfileVersion) { |
| 38 | + packageLockJson.lockfileVersion = 3; |
| 39 | + } |
| 40 | + |
| 41 | + // We use arborist to traverse the dependency graph correctly. It handles various edge cases such as |
| 42 | + // dependencies installed via "npm:xyz", which required special parsing (see package "@isaacs/cliui"). |
| 43 | + const arb = new Arborist({ |
| 44 | + path: workspaceRootDir, |
| 45 | + }); |
| 46 | + const tree = await arb.loadVirtual(); |
| 47 | + const cliNode = Array.from(tree.tops).find((node) => node.packageName === targetPackageName); |
| 48 | + if (!cliNode) { |
| 49 | + throw new Error(`Target package "${targetPackageName}" not found in workspace`); |
| 50 | + } |
| 51 | + |
| 52 | + const relevantPackageLocations = new Map(); |
| 53 | + // Collect all package keys using arborist |
| 54 | + collectDependencies(cliNode, relevantPackageLocations); |
| 55 | + |
| 56 | + // Using the keys, extract relevant package-entries from package-lock.json |
| 57 | + const extractedPackages = Object.create(null); |
| 58 | + for (let [packageLoc, node] of relevantPackageLocations) { |
| 59 | + let pkg = packageLockJson.packages[packageLoc]; |
| 60 | + if (pkg.link) { |
| 61 | + pkg = packageLockJson.packages[pkg.resolved]; |
| 62 | + } |
| 63 | + if (pkg.name === targetPackageName) { |
| 64 | + // Make the target package the root package |
| 65 | + packageLoc = ""; |
| 66 | + if (extractedPackages[packageLoc]) { |
| 67 | + throw new Error(`Duplicate root package entry for "${targetPackageName}"`); |
| 68 | + } |
| 69 | + } else if (!pkg.resolved) { |
| 70 | + // For all but the root package, ensure that "resolved" and "integrity" fields are present |
| 71 | + // These are always missing for locally linked packages, but sometimes also for others (e.g. if installed |
| 72 | + // from local cache) |
| 73 | + const {resolved, integrity} = await fetchPackageMetadata(node.packageName, node.version); |
| 74 | + pkg.resolved = resolved; |
| 75 | + pkg.integrity = integrity; |
| 76 | + } |
| 77 | + extractedPackages[packageLoc] = pkg; |
| 78 | + } |
| 79 | + |
| 80 | + // Sort packages by key to ensure consistent order (just like the npm cli does it) |
| 81 | + const sortedExtractedPackages = Object.create(null); |
| 82 | + const sortedKeys = Object.keys(extractedPackages).sort((a, b) => a.localeCompare(b)); |
| 83 | + for (const key of sortedKeys) { |
| 84 | + sortedExtractedPackages[key] = extractedPackages[key]; |
| 85 | + } |
| 86 | + |
| 87 | + // Generate npm-shrinkwrap.json |
| 88 | + const shrinkwrap = { |
| 89 | + name: targetPackageName, |
| 90 | + version: cliNode.version, |
| 91 | + lockfileVersion: 3, |
| 92 | + requires: true, |
| 93 | + packages: sortedExtractedPackages |
| 94 | + }; |
| 95 | + |
| 96 | + return shrinkwrap; |
| 97 | +} |
| 98 | + |
| 99 | +function collectDependencies(node, relevantPackageLocations) { |
| 100 | + if (relevantPackageLocations.has(node.location)) { |
| 101 | + // Already processed |
| 102 | + return; |
| 103 | + } |
| 104 | + relevantPackageLocations.set(node.location, node); |
| 105 | + if (node.isLink) { |
| 106 | + node = node.target; |
| 107 | + } |
| 108 | + for (const edge of node.edgesOut.values()) { |
| 109 | + if (edge.dev) { |
| 110 | + continue; |
| 111 | + } |
| 112 | + collectDependencies(edge.to, relevantPackageLocations); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Fetch package metadata from npm registry using pacote |
| 118 | + */ |
| 119 | +async function fetchPackageMetadata(packageName, version) { |
| 120 | + try { |
| 121 | + const spec = `${packageName}@${version}`; |
| 122 | + const manifest = await pacote.manifest(spec); |
| 123 | + |
| 124 | + return { |
| 125 | + resolved: manifest.dist.tarball, |
| 126 | + integrity: manifest.dist.integrity |
| 127 | + }; |
| 128 | + } catch (error) { |
| 129 | + throw new Error(`Could not fetch registry metadata for ${packageName}@${version}: ${error.message}`); |
| 130 | + } |
| 131 | +} |
0 commit comments