cve-lite-cli 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { findFiles, findNearestPackageJson, chooseBestLockfile, safeReadText, relativeOrName } from "../utils/file.js";
4
+ import { loadFromPackageJson } from "./package-json.js";
5
+ import { loadFromPackageLock } from "./package-lock.js";
6
+ import { loadFromPnpmLock } from "./pnpm-lock.js";
7
+ import { loadFromYarnLock } from "./yarn-lock.js";
8
+ export function loadPackages(projectRoot, prodOnly, maxDepth) {
9
+ const rootPackageLock = path.join(projectRoot, "package-lock.json");
10
+ const rootPnpmLock = path.join(projectRoot, "pnpm-lock.yaml");
11
+ const rootYarnLock = path.join(projectRoot, "yarn.lock");
12
+ if (fs.existsSync(rootPackageLock)) {
13
+ return {
14
+ mode: "resolved-lockfile",
15
+ source: "package-lock",
16
+ filePath: rootPackageLock,
17
+ packages: loadFromPackageLock(rootPackageLock, prodOnly),
18
+ notes: [
19
+ "Scanned resolved dependency versions from package-lock.json.",
20
+ "Dependency paths are derived from lockfile package locations."
21
+ ],
22
+ warnings: [],
23
+ skippedDependencies: []
24
+ };
25
+ }
26
+ if (fs.existsSync(rootPnpmLock)) {
27
+ return {
28
+ mode: "resolved-lockfile",
29
+ source: "pnpm-lock",
30
+ filePath: rootPnpmLock,
31
+ packages: loadFromPnpmLock(rootPnpmLock, prodOnly),
32
+ notes: [
33
+ "Scanned resolved dependency versions from pnpm-lock.yaml.",
34
+ "Dependency paths are approximated from importer relationships and package snapshots."
35
+ ],
36
+ warnings: [],
37
+ skippedDependencies: []
38
+ };
39
+ }
40
+ if (fs.existsSync(rootYarnLock)) {
41
+ return {
42
+ mode: "resolved-lockfile",
43
+ source: "yarn-lock",
44
+ filePath: rootYarnLock,
45
+ packages: loadFromYarnLock(rootYarnLock),
46
+ notes: [
47
+ "Scanned resolved dependency versions from yarn.lock.",
48
+ "Dependency path reconstruction is limited for Yarn Classic lockfiles in this MVP."
49
+ ],
50
+ warnings: [],
51
+ skippedDependencies: []
52
+ };
53
+ }
54
+ const discoveredLockfiles = findFiles(projectRoot, ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"], maxDepth);
55
+ if (discoveredLockfiles.length > 0) {
56
+ const selected = chooseBestLockfile(discoveredLockfiles);
57
+ const selectedName = path.basename(selected);
58
+ if (selectedName === "package-lock.json") {
59
+ return {
60
+ mode: "resolved-lockfile",
61
+ source: "package-lock",
62
+ filePath: selected,
63
+ packages: loadFromPackageLock(selected, prodOnly),
64
+ notes: [
65
+ `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
66
+ "Dependency paths are derived from lockfile package locations."
67
+ ],
68
+ warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
69
+ skippedDependencies: []
70
+ };
71
+ }
72
+ if (selectedName === "pnpm-lock.yaml") {
73
+ return {
74
+ mode: "resolved-lockfile",
75
+ source: "pnpm-lock",
76
+ filePath: selected,
77
+ packages: loadFromPnpmLock(selected, prodOnly),
78
+ notes: [
79
+ `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
80
+ "Dependency paths are approximated from importer relationships and package snapshots."
81
+ ],
82
+ warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
83
+ skippedDependencies: []
84
+ };
85
+ }
86
+ return {
87
+ mode: "resolved-lockfile",
88
+ source: "yarn-lock",
89
+ filePath: selected,
90
+ packages: loadFromYarnLock(selected),
91
+ notes: [
92
+ `Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
93
+ "Dependency path reconstruction is limited for Yarn Classic lockfiles in this MVP."
94
+ ],
95
+ warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
96
+ skippedDependencies: []
97
+ };
98
+ }
99
+ const packageJsonPath = findNearestPackageJson(projectRoot, maxDepth);
100
+ if (packageJsonPath) {
101
+ const manifestResult = loadFromPackageJson(packageJsonPath, prodOnly);
102
+ const warnings = [
103
+ "No supported lockfile was found, so the scanner fell back to package.json.",
104
+ "Manifest fallback can only check direct dependencies pinned to exact versions."
105
+ ];
106
+ const npmrcPath = path.join(path.dirname(packageJsonPath), ".npmrc");
107
+ if (fs.existsSync(npmrcPath)) {
108
+ const npmrc = safeReadText(npmrcPath);
109
+ if (/^\s*package-lock\s*=\s*false\s*$/m.test(npmrc)) {
110
+ warnings.push("This repo disables package-lock generation in .npmrc. For npm projects, try: npm install --package-lock-only --ignore-scripts --package-lock=true");
111
+ }
112
+ }
113
+ return {
114
+ mode: "manifest-fallback",
115
+ source: "package-json",
116
+ filePath: packageJsonPath,
117
+ packages: manifestResult.packages,
118
+ notes: [
119
+ `Scanned direct dependencies from ${relativeOrName(projectRoot, packageJsonPath)}.`,
120
+ "Manifest fallback does not resolve transitive dependencies unless they are pinned and present in a lockfile."
121
+ ],
122
+ warnings,
123
+ skippedDependencies: manifestResult.skippedDependencies
124
+ };
125
+ }
126
+ return {
127
+ mode: "manifest-fallback",
128
+ source: "unknown",
129
+ filePath: null,
130
+ packages: [],
131
+ notes: [],
132
+ warnings: [],
133
+ skippedDependencies: []
134
+ };
135
+ }
136
+ export function buildNoPackagesMessage(projectRoot) {
137
+ return [
138
+ "No scannable packages were found.",
139
+ "Supported inputs: package-lock.json, pnpm-lock.yaml, yarn.lock, or package.json with exact pinned versions.",
140
+ `Searched under: ${projectRoot}`
141
+ ].join(" ");
142
+ }
@@ -0,0 +1,37 @@
1
+ import fs from "node:fs";
2
+ import { parseExactManifestVersion } from "../utils/version.js";
3
+ import { upsertPackage } from "./utils.js";
4
+ export function loadFromPackageJson(filePath, prodOnly) {
5
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
6
+ const map = new Map();
7
+ const skipped = [];
8
+ const sections = [
9
+ { name: "dependencies", deps: raw.dependencies, dev: false },
10
+ { name: "optionalDependencies", deps: raw.optionalDependencies, dev: false }
11
+ ];
12
+ if (!prodOnly) {
13
+ sections.push({ name: "devDependencies", deps: raw.devDependencies, dev: true });
14
+ }
15
+ for (const section of sections) {
16
+ if (!section.deps || typeof section.deps !== "object")
17
+ continue;
18
+ for (const [name, spec] of Object.entries(section.deps)) {
19
+ const exactVersion = parseExactManifestVersion(String(spec));
20
+ if (!exactVersion) {
21
+ skipped.push(`${section.name}:${name}@${spec}`);
22
+ continue;
23
+ }
24
+ upsertPackage(map, {
25
+ name,
26
+ version: exactVersion,
27
+ ecosystem: "npm",
28
+ dev: section.dev,
29
+ paths: [["project", name]]
30
+ });
31
+ }
32
+ }
33
+ return {
34
+ packages: [...map.values()],
35
+ skippedDependencies: skipped.slice(0, 50)
36
+ };
37
+ }
@@ -0,0 +1,40 @@
1
+ import fs from "node:fs";
2
+ import { upsertPackage, normalizeNodeModulesPath } from "./utils.js";
3
+ export function loadFromPackageLock(filePath, prodOnly) {
4
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
5
+ const map = new Map();
6
+ if (raw.packages && typeof raw.packages === "object") {
7
+ for (const [pkgPath, meta] of Object.entries(raw.packages)) {
8
+ if (!pkgPath || pkgPath === "")
9
+ continue;
10
+ if (!pkgPath.includes("node_modules/"))
11
+ continue;
12
+ const name = pkgPath.slice(pkgPath.lastIndexOf("node_modules/") + "node_modules/".length);
13
+ const version = meta?.version;
14
+ const dev = !!meta?.dev;
15
+ if (!name || !version)
16
+ continue;
17
+ if (prodOnly && dev)
18
+ continue;
19
+ const pathParts = normalizeNodeModulesPath(pkgPath);
20
+ upsertPackage(map, { name, version, ecosystem: "npm", dev, paths: [pathParts] });
21
+ }
22
+ }
23
+ if (map.size === 0 && raw.dependencies && typeof raw.dependencies === "object") {
24
+ walkLegacyDeps(raw.dependencies, map, prodOnly, ["project"]);
25
+ }
26
+ return [...map.values()];
27
+ }
28
+ function walkLegacyDeps(deps, map, prodOnly, currentPath) {
29
+ for (const [name, meta] of Object.entries(deps)) {
30
+ const version = meta?.version;
31
+ const dev = !!meta?.dev;
32
+ const nextPath = [...currentPath, name];
33
+ if (name && version && !(prodOnly && dev)) {
34
+ upsertPackage(map, { name, version, ecosystem: "npm", dev, paths: [nextPath] });
35
+ }
36
+ if (meta?.dependencies) {
37
+ walkLegacyDeps(meta.dependencies, map, prodOnly, nextPath);
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,109 @@
1
+ import fs from "node:fs";
2
+ import YAML from "yaml";
3
+ import { looksLikeVersion, normalizeRawVersion } from "../utils/version.js";
4
+ import { upsertPackage } from "./utils.js";
5
+ import { uniquePathArrays } from "../utils/array.js";
6
+ export function loadFromPnpmLock(filePath, prodOnly) {
7
+ const content = fs.readFileSync(filePath, "utf8");
8
+ const parsed = YAML.parse(content);
9
+ const packagesSection = parsed?.packages ?? {};
10
+ const importers = parsed?.importers ?? {};
11
+ const graph = new Map();
12
+ const map = new Map();
13
+ for (const [key, meta] of Object.entries(packagesSection)) {
14
+ const ref = parsePnpmPackageKey(String(key));
15
+ if (!ref)
16
+ continue;
17
+ const depKeys = new Set();
18
+ for (const depMap of [meta?.dependencies, meta?.optionalDependencies]) {
19
+ if (!depMap || typeof depMap !== "object")
20
+ continue;
21
+ for (const [depName, depRef] of Object.entries(depMap)) {
22
+ const resolved = normalizePnpmDepRef(String(depName), depRef);
23
+ if (resolved)
24
+ depKeys.add(resolved);
25
+ }
26
+ }
27
+ graph.set(ref.key, [...depKeys]);
28
+ const dev = !!meta?.dev;
29
+ if (prodOnly && dev)
30
+ continue;
31
+ upsertPackage(map, { name: ref.name, version: ref.version, ecosystem: "npm", dev, paths: [] });
32
+ }
33
+ const rootDeps = [];
34
+ for (const importer of Object.values(importers)) {
35
+ for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
36
+ if (prodOnly && depSectionName == "devDependencies")
37
+ continue;
38
+ const depSection = importer?.[depSectionName];
39
+ if (!depSection || typeof depSection !== "object")
40
+ continue;
41
+ for (const [depName, depRef] of Object.entries(depSection)) {
42
+ const resolved = normalizePnpmDepRef(String(depName), depRef);
43
+ if (resolved) {
44
+ rootDeps.push(resolved);
45
+ }
46
+ else {
47
+ const fallbackVersion = normalizeRawVersion(depRef);
48
+ if (fallbackVersion) {
49
+ upsertPackage(map, {
50
+ name: String(depName),
51
+ version: fallbackVersion,
52
+ ecosystem: "npm",
53
+ paths: [["project", String(depName)]]
54
+ });
55
+ }
56
+ }
57
+ }
58
+ }
59
+ }
60
+ const queue = rootDeps.map(dep => ({ key: dep, path: ["project"] }));
61
+ const seenPaths = new Set();
62
+ while (queue.length > 0) {
63
+ const current = queue.shift();
64
+ const ref = parsePnpmPackageKey(current.key);
65
+ if (!ref)
66
+ continue;
67
+ const nextPath = [...current.path, ref.name];
68
+ const pathFingerprint = `${current.key}|${nextPath.join(">")}`;
69
+ if (seenPaths.has(pathFingerprint))
70
+ continue;
71
+ seenPaths.add(pathFingerprint);
72
+ const pkgKey = `${ref.name}@${ref.version}`;
73
+ const pkg = map.get(pkgKey);
74
+ if (pkg) {
75
+ pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, 5);
76
+ }
77
+ const children = graph.get(current.key) ?? [];
78
+ for (const child of children) {
79
+ queue.push({ key: child, path: nextPath });
80
+ }
81
+ }
82
+ return [...map.values()];
83
+ }
84
+ function parsePnpmPackageKey(key) {
85
+ const cleaned = key.replace(/^\//, "").split("(")[0];
86
+ const match = cleaned.match(/^(@?[^/]+(?:\/[^/]+)?)\/([^/]+)$/);
87
+ if (!match)
88
+ return null;
89
+ const [, name, version] = match;
90
+ return { key, name, version };
91
+ }
92
+ function normalizePnpmDepRef(depName, depRef) {
93
+ if (typeof depRef === "string") {
94
+ const cleaned = depRef.replace(/^link:/, "").replace(/^workspace:/, "").split("(")[0];
95
+ if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
96
+ return null;
97
+ if (cleaned.startsWith("/"))
98
+ return cleaned;
99
+ if (cleaned.includes("/"))
100
+ return "/" + cleaned.replace(/^\//, "");
101
+ if (looksLikeVersion(cleaned))
102
+ return `/${depName}/${cleaned}`;
103
+ }
104
+ if (depRef && typeof depRef === "object") {
105
+ const version = depRef.version ?? depRef.specifier;
106
+ return normalizePnpmDepRef(depName, version);
107
+ }
108
+ return null;
109
+ }
@@ -0,0 +1,32 @@
1
+ import { uniquePathArrays } from "../utils/array.js";
2
+ export function upsertPackage(map, candidate) {
3
+ const key = `${candidate.name}@${candidate.version}`;
4
+ const existing = map.get(key);
5
+ if (!existing) {
6
+ map.set(key, { ...candidate, paths: uniquePathArrays(candidate.paths ?? []).slice(0, 5) });
7
+ return;
8
+ }
9
+ existing.dev = existing.dev && candidate.dev;
10
+ existing.paths = uniquePathArrays([...(existing.paths ?? []), ...(candidate.paths ?? [])]).slice(0, 5);
11
+ }
12
+ export function normalizeNodeModulesPath(pkgPath) {
13
+ const parts = pkgPath.split("/").filter(Boolean);
14
+ const names = ["project"];
15
+ for (let i = 0; i < parts.length; i++) {
16
+ if (parts[i] !== "node_modules")
17
+ continue;
18
+ const next = parts[i + 1];
19
+ const scopedNext = parts[i + 2];
20
+ if (!next)
21
+ continue;
22
+ if (next.startsWith("@") && scopedNext) {
23
+ names.push(`${next}/${scopedNext}`);
24
+ i += 2;
25
+ }
26
+ else {
27
+ names.push(next);
28
+ i += 1;
29
+ }
30
+ }
31
+ return names;
32
+ }
@@ -0,0 +1,25 @@
1
+ import fs from "node:fs";
2
+ import { parse as parseYarnLock } from "yarn-lockfile";
3
+ import { upsertPackage } from "./utils.js";
4
+ export function loadFromYarnLock(filePath) {
5
+ const content = fs.readFileSync(filePath, "utf8");
6
+ const parsed = parseYarnLock(content);
7
+ if (parsed.type !== "success" || !parsed.object) {
8
+ throw new Error("Could not parse yarn.lock");
9
+ }
10
+ const map = new Map();
11
+ for (const [selector, meta] of Object.entries(parsed.object)) {
12
+ const version = meta?.version;
13
+ if (!version)
14
+ continue;
15
+ const firstSelector = String(selector).split(",")[0].trim();
16
+ const atIndex = firstSelector.lastIndexOf("@");
17
+ if (atIndex <= 0)
18
+ continue;
19
+ const name = firstSelector.slice(0, atIndex);
20
+ if (!name || !version)
21
+ continue;
22
+ upsertPackage(map, { name, version, ecosystem: "npm", paths: [["project", name]] });
23
+ }
24
+ return [...map.values()];
25
+ }
@@ -0,0 +1,137 @@
1
+ import { chunk, unique } from "./utils/array.js";
2
+ import { compareVersions, looksLikeVersion } from "./utils/version.js";
3
+ import { loadCache, saveCache } from "./osv/cache.js";
4
+ import { maxSeverity } from "./osv/severity.js";
5
+ import { createSpinner } from "./output/spinner.js";
6
+ import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js";
7
+ export function createAdvisorySource(options) {
8
+ return new OsvAdvisorySource(options?.osvUrl);
9
+ }
10
+ export async function scanPackages(packages, batchSize, options) {
11
+ const offline = !!options.offline;
12
+ const cacheDirOverride = options.cacheDir;
13
+ const spinner = createSpinner("Scanning dependencies against OSV...", options);
14
+ const advisorySource = createAdvisorySource({ osvUrl: options.osvUrl });
15
+ try {
16
+ const chunks = chunk(packages, batchSize);
17
+ const results = [];
18
+ if (!offline) {
19
+ for (let i = 0; i < chunks.length; i++) {
20
+ spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
21
+ const chunkItems = chunks[i];
22
+ const advisoryResult = await advisorySource.queryBatch(chunkItems);
23
+ const rows = advisoryResult ?? [];
24
+ for (let j = 0; j < chunkItems.length; j++) {
25
+ const pkg = chunkItems[j];
26
+ const row = rows[j];
27
+ const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
28
+ if (vulnIds.length > 0) {
29
+ results.push({ pkg, vulnIds });
30
+ }
31
+ }
32
+ }
33
+ spinner.succeed(`Queried OSV in ${chunks.length} batch${chunks.length === 1 ? "" : "es"}`);
34
+ }
35
+ else {
36
+ spinner.succeed("Offline mode enabled; package matching was skipped");
37
+ }
38
+ const cache = loadCache(cacheDirOverride);
39
+ const idSet = new Set(results.flatMap(r => r.vulnIds));
40
+ const vulnMap = new Map();
41
+ if (idSet.size > 0 && !offline) {
42
+ const ids = [...idSet];
43
+ const detailSpinner = createSpinner("Fetching vulnerability details...", options);
44
+ try {
45
+ for (let i = 0; i < ids.length; i++) {
46
+ const id = ids[i];
47
+ detailSpinner.update(`Fetching vulnerability details ${i + 1}/${ids.length}...`);
48
+ const cached = cache.entries[id];
49
+ if (cached) {
50
+ vulnMap.set(id, cached);
51
+ continue;
52
+ }
53
+ try {
54
+ const detail = await advisorySource.getVuln(id);
55
+ vulnMap.set(id, detail);
56
+ cache.entries[id] = detail;
57
+ }
58
+ catch (_error) {
59
+ cache.entries[id] = null;
60
+ }
61
+ }
62
+ detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail record${ids.length === 1 ? "" : "s"}`);
63
+ }
64
+ catch (error) {
65
+ detailSpinner.fail("Failed while fetching vulnerability details");
66
+ throw error;
67
+ }
68
+ }
69
+ if (!offline && idSet.size > 0) {
70
+ saveCache(cache, cacheDirOverride);
71
+ }
72
+ return results.map(result => {
73
+ const vulnerabilities = result.vulnIds
74
+ .map(id => vulnMap.get(id))
75
+ .filter((v) => Boolean(v));
76
+ const severity = maxSeverity(vulnerabilities);
77
+ const cveAliases = unique(vulnerabilities.flatMap(v => (v.aliases ?? []).filter(a => a.startsWith("CVE-"))));
78
+ const dependencyPaths = result.pkg.paths ?? [];
79
+ const relationship = classifyRelationship(dependencyPaths);
80
+ const firstFixedVersion = findFirstFixedVersion(vulnerabilities);
81
+ return {
82
+ pkg: result.pkg,
83
+ vulnerabilities,
84
+ severity,
85
+ cveAliases,
86
+ dependencyPaths,
87
+ relationship,
88
+ firstFixedVersion
89
+ };
90
+ });
91
+ }
92
+ catch (error) {
93
+ spinner.fail("Scan failed");
94
+ throw error;
95
+ }
96
+ }
97
+ function classifyRelationship(paths) {
98
+ if (paths.length === 0)
99
+ return "unknown";
100
+ const shortest = Math.min(...paths.map(p => p.length));
101
+ if (shortest <= 2)
102
+ return "direct";
103
+ return "transitive";
104
+ }
105
+ function findFirstFixedVersion(vulns) {
106
+ const fixedVersions = [];
107
+ for (const vuln of vulns) {
108
+ for (const affected of vuln.affected ?? []) {
109
+ for (const range of affected.ranges ?? []) {
110
+ for (const event of range.events ?? []) {
111
+ const fixed = event.fixed;
112
+ if (fixed && looksLikeVersion(fixed)) {
113
+ fixedVersions.push(fixed);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+ if (fixedVersions.length === 0)
120
+ return null;
121
+ return fixedVersions.sort(compareVersions)[0];
122
+ }
123
+ export function buildCoverageNotes(scanInput, offline) {
124
+ const notes = [
125
+ "This MVP checks package versions against OSV advisories. It does not prove exploitability or runtime reachability.",
126
+ "Installed node_modules contents are not verified in this scan.",
127
+ "Container images, binaries, secrets, and IaC files are not scanned.",
128
+ "Monorepo workspace boundaries are only partially modeled in this version."
129
+ ];
130
+ if (scanInput.mode === "manifest-fallback") {
131
+ notes.push("Manifest fallback is limited to direct dependencies pinned to exact versions. It does not resolve transitive dependencies from package.json alone.");
132
+ }
133
+ if (offline) {
134
+ notes.push("Offline mode only uses cached vulnerability details.");
135
+ }
136
+ return notes;
137
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ export function chunk(items, size) {
2
+ const output = [];
3
+ for (let i = 0; i < items.length; i += size) {
4
+ output.push(items.slice(i, i + size));
5
+ }
6
+ return output;
7
+ }
8
+ export function unique(items) {
9
+ return [...new Set(items)];
10
+ }
11
+ export function uniquePathArrays(paths) {
12
+ const seen = new Set();
13
+ const output = [];
14
+ for (const item of paths) {
15
+ const key = item.join(">");
16
+ if (seen.has(key))
17
+ continue;
18
+ seen.add(key);
19
+ output.push(item);
20
+ }
21
+ return output;
22
+ }
@@ -0,0 +1,48 @@
1
+ import process from "node:process";
2
+ const ansi = {
3
+ reset: "\x1b[0m",
4
+ bold: "\x1b[1m",
5
+ red: "\x1b[31m",
6
+ redBright: "\x1b[91m",
7
+ green: "\x1b[32m",
8
+ greenBright: "\x1b[92m",
9
+ yellow: "\x1b[33m",
10
+ blue: "\x1b[34m",
11
+ blueBright: "\x1b[94m",
12
+ magenta: "\x1b[35m",
13
+ cyan: "\x1b[36m",
14
+ white: "\x1b[37m",
15
+ whiteBright: "\x1b[97m",
16
+ gray: "\x1b[90m"
17
+ };
18
+ const colorEnabled = Boolean(process.stdout.isTTY) && process.env.NO_COLOR !== "1";
19
+ function paint(code, text) {
20
+ if (!colorEnabled)
21
+ return text;
22
+ return `${code}${text}${ansi.reset}`;
23
+ }
24
+ export const chalk = {
25
+ bold: Object.assign((text) => paint(ansi.bold, text), {
26
+ cyan: (text) => paint(ansi.bold + ansi.cyan, text),
27
+ green: (text) => paint(ansi.bold + ansi.green, text),
28
+ magenta: (text) => paint(ansi.bold + ansi.magenta, text),
29
+ blue: (text) => paint(ansi.bold + ansi.blue, text),
30
+ yellow: (text) => paint(ansi.bold + ansi.yellow, text),
31
+ whiteBright: (text) => paint(ansi.bold + ansi.whiteBright, text)
32
+ }),
33
+ cyan: (text) => paint(ansi.cyan, text),
34
+ green: (text) => paint(ansi.green, text),
35
+ greenBright: (text) => paint(ansi.greenBright, text),
36
+ red: (text) => paint(ansi.red, text),
37
+ redBright: (text) => paint(ansi.redBright, text),
38
+ yellow: (text) => paint(ansi.yellow, text),
39
+ blue: (text) => paint(ansi.blue, text),
40
+ blueBright: (text) => paint(ansi.blueBright, text),
41
+ magenta: (text) => paint(ansi.magenta, text),
42
+ gray: (text) => paint(ansi.gray, text),
43
+ white: (text) => paint(ansi.white, text),
44
+ whiteBright: (text) => paint(ansi.whiteBright, text)
45
+ };
46
+ export function stripAnsi(text) {
47
+ return text.replace(/\x1b\[[0-9;]*m/g, "");
48
+ }
@@ -0,0 +1,74 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { EXCLUDED_DIRS } from "../constants.js";
4
+ export function safeReadText(filePath) {
5
+ try {
6
+ return fs.readFileSync(filePath, "utf8");
7
+ }
8
+ catch (_error) {
9
+ return "";
10
+ }
11
+ }
12
+ export function relativeOrName(rootDir, filePath) {
13
+ const relative = path.relative(rootDir, filePath);
14
+ return relative || path.basename(filePath);
15
+ }
16
+ export function findFiles(rootDir, names, maxDepth) {
17
+ const results = [];
18
+ function walk(currentDir, depth) {
19
+ if (depth > maxDepth)
20
+ return;
21
+ let entries = [];
22
+ try {
23
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
24
+ }
25
+ catch (_error) {
26
+ return;
27
+ }
28
+ for (const entry of entries) {
29
+ const fullPath = path.join(currentDir, entry.name);
30
+ if (entry.isFile() && names.includes(entry.name)) {
31
+ results.push(fullPath);
32
+ }
33
+ }
34
+ for (const entry of entries) {
35
+ if (!entry.isDirectory())
36
+ continue;
37
+ if (EXCLUDED_DIRS.has(entry.name))
38
+ continue;
39
+ walk(path.join(currentDir, entry.name), depth + 1);
40
+ }
41
+ }
42
+ walk(rootDir, 0);
43
+ return results.sort((a, b) => {
44
+ const aDepth = a.split(path.sep).length;
45
+ const bDepth = b.split(path.sep).length;
46
+ return aDepth - bDepth || a.localeCompare(b);
47
+ });
48
+ }
49
+ export function findNearestPackageJson(projectRoot, maxDepth) {
50
+ const rootCandidate = path.join(projectRoot, "package.json");
51
+ if (fs.existsSync(rootCandidate))
52
+ return rootCandidate;
53
+ const found = findFiles(projectRoot, ["package.json"], maxDepth);
54
+ return found[0] ?? null;
55
+ }
56
+ export function chooseBestLockfile(candidates) {
57
+ return [...candidates].sort((a, b) => {
58
+ const aDepth = a.split(path.sep).length;
59
+ const bDepth = b.split(path.sep).length;
60
+ if (aDepth !== bDepth)
61
+ return aDepth - bDepth;
62
+ const score = (file) => {
63
+ const name = path.basename(file);
64
+ if (name === "package-lock.json")
65
+ return 0;
66
+ if (name === "pnpm-lock.yaml")
67
+ return 1;
68
+ if (name === "yarn.lock")
69
+ return 2;
70
+ return 3;
71
+ };
72
+ return score(a) - score(b);
73
+ })[0];
74
+ }