From 9758086b4fd287ac6ae2477d6b470f697bf508c1 Mon Sep 17 00:00:00 2001 From: divyanshujethi Date: Thu, 26 Nov 2026 22:00:53 +0530 Subject: [PATCH] feat(engines): Phase 4 Tier 2 manifest-rewriting ecosystems (JVM, Elixir, Apple/Swift) --- src/cli.ts | 2 +- src/compliance/osv.ts | 22 +- src/compliance/sbom.ts | 8 +- src/dispatcher/executor.ts | 10 + src/doctor/checker.ts | 56 ++++ src/engines/base.ts | 16 + src/engines/declarative.ts | 26 ++ src/engines/index.ts | 11 + src/engines/mutators/apple.ts | 209 +++++++++++++ src/engines/mutators/elixir.ts | 111 +++++++ src/engines/mutators/file-helpers.ts | 40 +++ src/engines/mutators/jvm.ts | 328 ++++++++++++++++++++ src/engines/registry.ts | 4 + src/engines/tier2-manifest.ts | 323 +++++++++++++++++++ src/outdated/checker.ts | 165 +++++++++- src/outdated/upgrader.ts | 42 +++ src/security/registry.ts | 146 +++++++++ src/types.ts | 10 +- src/workspace/crypto.ts | 195 ++++++++++++ tests/completion.test.ts | 8 + tests/phase4-tier2-manifest.test.ts | 448 +++++++++++++++++++++++++++ 21 files changed, 2168 insertions(+), 12 deletions(-) create mode 100644 src/engines/mutators/apple.ts create mode 100644 src/engines/mutators/elixir.ts create mode 100644 src/engines/mutators/file-helpers.ts create mode 100644 src/engines/mutators/jvm.ts create mode 100644 src/engines/tier2-manifest.ts create mode 100644 tests/phase4-tier2-manifest.test.ts diff --git a/src/cli.ts b/src/cli.ts index b66a67f..0007a7e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -90,7 +90,7 @@ COMMANDS: mcp [install] Start stdio MCP server or 1-click install for Claude Desktop, Cursor, Windsurf init [--ide] Initialize workspace or generate AI agent guidelines (.cursorrules, CLAUDE.md) completion Generate native shell tab auto-completion (bash, zsh, fish, powershell) - which Show active CLI binary for an ecosystem (npm, jsr, pypi, conda, cargo, go, nuget, composer, gem, pub, conan, vcpkg, meson, julia) + which Show active CLI binary for an ecosystem (npm, jsr, pypi, conda, cargo, go, nuget, composer, gem, pub, conan, vcpkg, meson, julia, maven, gradle, sbt, hex, rebar3, swift, cocoapods, carthage) OPTIONS: -D, --dev Install as a development dependency diff --git a/src/compliance/osv.ts b/src/compliance/osv.ts index 829689d..81ea911 100644 --- a/src/compliance/osv.ts +++ b/src/compliance/osv.ts @@ -68,13 +68,21 @@ export class OsvClient { return []; } - const queries: OsvQueryItem[] = queryable.map(({ pkg, osvEcosystem }) => ({ - package: { - name: pkg.name, - ecosystem: osvEcosystem, - }, - version: pkg.version.replace(/^[~^>=<\s]+/, "").trim(), - })); + const queries: OsvQueryItem[] = queryable.map(({ pkg, osvEcosystem }) => { + let osvName = pkg.name; + if (osvEcosystem === "Maven" && osvName.includes("/")) { + osvName = osvName.replace("/", ":"); + } else if (osvEcosystem === "SwiftURL") { + osvName = osvName.replace(/^https?:\/\//i, "").replace(/\.git$/i, ""); + } + return { + package: { + name: osvName, + ecosystem: osvEcosystem, + }, + version: pkg.version.replace(/^[~^>=<\s]+/, "").trim(), + }; + }); try { const response = await fetch(OsvClient.OSV_BATCH_URL, { diff --git a/src/compliance/sbom.ts b/src/compliance/sbom.ts index 3606098..138df39 100644 --- a/src/compliance/sbom.ts +++ b/src/compliance/sbom.ts @@ -42,11 +42,13 @@ export class SbomGenerator { const components = packages.map((pkg) => { const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem); const cleanVer = pkg.version.replace(/^[~^>=<\s]+/, ""); + const purlName = + purlEcosystem === "maven" ? pkg.packageName.replace(":", "/") : pkg.packageName; return { type: "library", name: pkg.packageName, version: cleanVer, - purl: `pkg:${purlEcosystem}/${pkg.packageName}@${cleanVer}`, + purl: `pkg:${purlEcosystem}/${purlName}@${cleanVer}`, licenses: [ { license: { @@ -91,6 +93,8 @@ export class SbomGenerator { const spdxPackages = packages.map((pkg, idx) => { const safeId = pkg.packageName.replace(/[^a-zA-Z0-9]/g, "-"); const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem); + const purlName = + purlEcosystem === "maven" ? pkg.packageName.replace(":", "/") : pkg.packageName; return { name: pkg.packageName, SPDXID: `SPDXRef-Package-${safeId}-${idx}`, @@ -104,7 +108,7 @@ export class SbomGenerator { { referenceCategory: "PACKAGE-MANAGER", referenceType: "purl", - referenceLocator: `pkg:${purlEcosystem}/${pkg.packageName}@${pkg.version.replace(/^[~^>=<]/, "")}`, + referenceLocator: `pkg:${purlEcosystem}/${purlName}@${pkg.version.replace(/^[~^>=<]/, "")}`, }, ], }; diff --git a/src/dispatcher/executor.ts b/src/dispatcher/executor.ts index 466aa26..d23ae15 100644 --- a/src/dispatcher/executor.ts +++ b/src/dispatcher/executor.ts @@ -78,6 +78,12 @@ export class PolyDispatcher { logExecutionPlan("add", pkg, engine.name, command, finalArgs); } + // 4.5 Apply Tier 2 manifest mutation if supported by engine (JVM, Elixir, Swift) + const mutation = engine.applyManifestAdd?.(pkg, cwd); + if (mutation?.changed && !options?.silent && !options?.agent) { + logInfo(`[manifest] Updated ${mutation.manifestFile}`); + } + // 5. Execute native command const result = await engine.execute(command, finalArgs, cwd, { silent: options?.silent || options?.agent, @@ -102,6 +108,10 @@ export class PolyDispatcher { } const engine = this.getEngineForEcosystem(pkg.ecosystem, cwd); + const mutation = engine.applyManifestRemove?.(pkg, cwd); + if (mutation?.changed && !options?.silent && !options?.agent) { + logInfo(`[manifest] Updated ${mutation.manifestFile}`); + } const { command, args } = engine.resolveRemoveArgs(pkg); if (!options?.silent) { diff --git a/src/doctor/checker.ts b/src/doctor/checker.ts index b0e6038..31823a2 100644 --- a/src/doctor/checker.ts +++ b/src/doctor/checker.ts @@ -305,6 +305,62 @@ export class PolyDoctor { args: ["--version"], hint: "https://julialang.org/downloads/", }, + { + id: "toolchain-maven", + name: "Apache Maven", + cmd: "mvn", + args: ["--version"], + hint: "https://maven.apache.org", + }, + { + id: "toolchain-gradle", + name: "Gradle Build Tool", + cmd: "gradle", + args: ["--version"], + hint: "https://gradle.org", + }, + { + id: "toolchain-sbt", + name: "Scala sbt", + cmd: "sbt", + args: ["--version"], + hint: "https://www.scala-sbt.org", + }, + { + id: "toolchain-elixir", + name: "Elixir Mix", + cmd: "mix", + args: ["--version"], + hint: "https://elixir-lang.org", + }, + { + id: "toolchain-rebar3", + name: "Erlang Rebar3", + cmd: "rebar3", + args: ["version"], + hint: "https://rebar3.org", + }, + { + id: "toolchain-swift", + name: "Swift Package Manager", + cmd: "swift", + args: ["--version"], + hint: "https://www.swift.org", + }, + { + id: "toolchain-cocoapods", + name: "CocoaPods", + cmd: "pod", + args: ["--version"], + hint: "https://cocoapods.org", + }, + { + id: "toolchain-carthage", + name: "Carthage", + cmd: "carthage", + args: ["version"], + hint: "https://github.com/Carthage/Carthage", + }, ]; for (const tc of toolchains) { diff --git a/src/engines/base.ts b/src/engines/base.ts index e21af79..432b3f2 100644 --- a/src/engines/base.ts +++ b/src/engines/base.ts @@ -46,6 +46,22 @@ export abstract class BaseEngine { */ abstract resolveUpdateArgs(pkg?: PackageSpec): { command: string; args: string[] }; + /** + * Optional manifest mutation hook executed before running add CLI commands (for Tier 2 ecosystems). + */ + applyManifestAdd?( + pkg: PackageSpec, + cwd: string, + ): { manifestFile: string; changed: boolean } | null; + + /** + * Optional manifest mutation hook executed before running remove CLI commands (for Tier 2 ecosystems). + */ + applyManifestRemove?( + pkg: PackageSpec, + cwd: string, + ): { manifestFile: string; changed: boolean } | null; + /** * Executes a native command asynchronously with performance timing. */ diff --git a/src/engines/declarative.ts b/src/engines/declarative.ts index da9f8c6..53a16dc 100644 --- a/src/engines/declarative.ts +++ b/src/engines/declarative.ts @@ -13,6 +13,18 @@ export interface DeclarativeCommandSpec { install: (ctx?: EngineContext) => string[]; /** Formats dependency update command arguments. */ update: (pkg?: PackageSpec, ctx?: EngineContext) => string[]; + /** Optional Tier 2 manifest mutator executed prior to CLI add command. */ + mutateAdd?: ( + pkg: PackageSpec, + cwd: string, + ctx?: EngineContext, + ) => { manifestFile: string; changed: boolean } | null; + /** Optional Tier 2 manifest mutator executed prior to CLI remove command. */ + mutateRemove?: ( + pkg: PackageSpec, + cwd: string, + ctx?: EngineContext, + ) => { manifestFile: string; changed: boolean } | null; } export interface EngineAdapter { @@ -92,6 +104,20 @@ export class DeclarativeEngine extends BaseEngine { resolveUpdateArgs(pkg?: PackageSpec): { command: string; args: string[] } { return { command: this.activeCommand, args: this.spec.update(pkg, this.ctx) }; } + + override applyManifestAdd( + pkg: PackageSpec, + cwd: string, + ): { manifestFile: string; changed: boolean } | null { + return this.spec.mutateAdd ? this.spec.mutateAdd(pkg, cwd, this.ctx) : null; + } + + override applyManifestRemove( + pkg: PackageSpec, + cwd: string, + ): { manifestFile: string; changed: boolean } | null { + return this.spec.mutateRemove ? this.spec.mutateRemove(pkg, cwd, this.ctx) : null; + } } /** diff --git a/src/engines/index.ts b/src/engines/index.ts index e43004a..053d756 100644 --- a/src/engines/index.ts +++ b/src/engines/index.ts @@ -13,6 +13,17 @@ export { mesonAdapter, vcpkgAdapter, } from "./cpp-julia.js"; +export { + TIER2_MANIFEST_ADAPTERS, + carthageAdapter, + cocoapodsAdapter, + gradleAdapter, + hexAdapter, + mavenAdapter, + rebar3Adapter, + sbtAdapter, + swiftAdapter, +} from "./tier2-manifest.js"; export { DeclarativeEngine, defineDeclarativeAdapter, diff --git a/src/engines/mutators/apple.ts b/src/engines/mutators/apple.ts new file mode 100644 index 0000000..ed0fb96 --- /dev/null +++ b/src/engines/mutators/apple.ts @@ -0,0 +1,209 @@ +import type { PackageSpec } from "../../types.js"; +import { cleanVersionSpec, escapeRegex } from "./file-helpers.js"; + +export interface SwiftTargetSpec { + url: string; + packageName: string; + productName: string; + version?: string; +} + +/** + * Normalizes Swift Package Manager URL/product specifiers from shorthands or PURLs. + */ +export function normalizeSwiftPackageSpec(pkg: PackageSpec): SwiftTargetSpec { + const rawName = pkg.namespace ? `${pkg.namespace}/${pkg.name}` : pkg.name; + const version = cleanVersionSpec(pkg.version); + + let url = rawName; + if (/^https?:\/\//i.test(rawName)) { + url = rawName.endsWith(".git") ? rawName : `${rawName}.git`; + } else if (/^[a-z0-9.-]+\.[a-z]{2,}\//i.test(rawName)) { + url = `https://${rawName.endsWith(".git") ? rawName : `${rawName}.git`}`; + } else if (rawName.includes("/")) { + url = `https://github.com/${rawName.endsWith(".git") ? rawName : `${rawName}.git`}`; + } + + const repoTail = + rawName + .replace(/\.git$/i, "") + .split("/") + .pop() ?? rawName; + return { + url, + packageName: repoTail, + productName: repoTail, + version, + }; +} + +/** + * Safely mutates Apple `Package.swift` (package-level `dependencies:` + `.target` link). + */ +export function mutatePackageSwift( + content: string, + action: "add" | "remove", + pkg: PackageSpec, +): string { + const spec = normalizeSwiftPackageSpec(pkg); + const urlNoGit = spec.url.replace(/\.git$/i, ""); + const urlEsc = escapeRegex(urlNoGit); + const pkgNameEsc = escapeRegex(spec.packageName); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + + const pkgDepRegex = new RegExp( + `^[ \\t]*\\.package\\(\\s*url:\\s*["']${urlEsc}(?:\\.git)?["'][^\\r\\n]*\\),?\\r?\\n?`, + "m", + ); + const productDepRegex = new RegExp( + `^[ \\t]*\\.product\\([^\\r\\n]*package:\\s*["']${pkgNameEsc}["'][^\\r\\n]*\\),?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(pkgDepRegex, "").replace(productDepRegex, ""); + } + + const ver = spec.version ?? "1.0.0"; + let next = content; + + const existingPkg = next.match(pkgDepRegex); + if (existingPkg) { + const updatedPkg = existingPkg[0].replace( + /(\b(?:from|exact)\s*:\s*["'])([^"']+)(["'])/, + `$1${ver}$3`, + ); + next = next.replace(existingPkg[0], updatedPkg); + } else { + const pkgDecl = `.package(url: "${spec.url}", from: "${ver}"),`; + const rootDepsMatch = next.match(/(^[ \t]*dependencies\s*:\s*\[)([\s\S]*?)(\r?\n[ \t]*\])/m); + if (rootDepsMatch) { + const inner = rootDepsMatch[2]; + const baseIndent = rootDepsMatch[1].match(/^[ \t]*/)?.[0] ?? " "; + const itemIndent = `${baseIndent} `; + if (inner.trim().length === 0) { + next = next.replace( + rootDepsMatch[0], + `${rootDepsMatch[1]}${eol}${itemIndent}${pkgDecl}${rootDepsMatch[3]}`, + ); + } else { + const stripped = inner.replace(/\s+$/, ""); + const needsComma = !stripped.endsWith(","); + next = next.replace( + rootDepsMatch[0], + `${rootDepsMatch[1]}${stripped}${needsComma ? "," : ""}${eol}${itemIndent}${pkgDecl}${rootDepsMatch[3]}`, + ); + } + } else { + next = next.replace( + /(^[ \t]*)(dependencies\s*:\s*)\[\s*\]/m, + `$1$2[${eol}$1 ${pkgDecl}${eol}$1]`, + ); + } + } + + if (!productDepRegex.test(next)) { + const targetBlockRegex = + /((\.(?:executableTarget|target)\([\s\S]*?^[ \t]*dependencies\s*:\s*)\[)([\s\S]*?)(\r?\n([ \t]*)\])/m; + const tMatch = next.match(targetBlockRegex); + if (tMatch) { + const inner = tMatch[3]; + const baseIndent = tMatch[5] ?? " "; + const itemIndent = `${baseIndent} `; + const prodLine = `.product(name: "${spec.productName}", package: "${spec.packageName}"),`; + if (inner.trim().length === 0) { + next = next.replace(tMatch[0], `${tMatch[2]}[${eol}${itemIndent}${prodLine}${tMatch[4]}`); + } else { + const stripped = inner.replace(/\s+$/, ""); + const needsComma = !stripped.endsWith(","); + next = next.replace( + tMatch[0], + `${tMatch[2]}[${stripped}${needsComma ? "," : ""}${eol}${itemIndent}${prodLine}${tMatch[4]}`, + ); + } + } else { + const inlineTargetDeps = + /(\.(?:executableTarget|target)\([\s\S]*?^([ \t]*)dependencies\s*:\s*)\[\s*\]/m; + const inlineMatch = next.match(inlineTargetDeps); + if (inlineMatch) { + const indent = inlineMatch[2] ?? " "; + const prodLine = `.product(name: "${spec.productName}", package: "${spec.packageName}"),`; + next = next.replace( + inlineMatch[0], + `${inlineMatch[1]}[${eol}${indent} ${prodLine}${eol}${indent}]`, + ); + } + } + } + + return next; +} + +/** + * Safely mutates CocoaPods `Podfile`. + */ +export function mutatePodfile(content: string, action: "add" | "remove", pkg: PackageSpec): string { + const podEsc = escapeRegex(pkg.name); + const podLineRegex = new RegExp( + `^[ \\t]*pod\\s+["']${podEsc}["'](?:\\s*,\\s*["']([^"']+)["'])?[^\\r\\n]*\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(podLineRegex, ""); + } + + const cleanVer = cleanVersionSpec(pkg.version); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const newPodLine = cleanVer ? `pod '${pkg.name}', '~> ${cleanVer}'` : `pod '${pkg.name}'`; + + const existing = content.match(podLineRegex); + if (existing) { + const indent = existing[0].match(/^[ \t]*/)?.[0] ?? " "; + return content.replace(existing[0], `${indent}${newPodLine}${eol}`); + } + + const targetMatch = content.match(/(^[ \t]*target\s+["'][^"']+["']\s+do\r?\n)/m); + if (targetMatch) { + const targetIndent = targetMatch[1].match(/^[ \t]*/)?.[0] ?? ""; + const itemIndent = `${targetIndent} `; + return content.replace(targetMatch[0], `${targetMatch[0]}${itemIndent}${newPodLine}${eol}`); + } + + const sep = content.length === 0 || content.endsWith("\n") ? "" : eol; + return `${content}${sep}${newPodLine}${eol}`; +} + +/** + * Safely mutates Carthage `Cartfile`. + */ +export function mutateCartfile( + content: string, + action: "add" | "remove", + pkg: PackageSpec, +): string { + const fullName = pkg.namespace ? `${pkg.namespace}/${pkg.name}` : pkg.name; + const escapedName = escapeRegex(fullName); + const entryRegex = new RegExp( + `^(?:github|git|binary)\\s+["']${escapedName}["'][^\\r\\n]*\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(entryRegex, ""); + } + + const cleanVer = cleanVersionSpec(pkg.version); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const constraint = cleanVer ? ` ~> ${cleanVer}` : ""; + const origin = fullName.startsWith("http") ? "git" : "github"; + const line = `${origin} "${fullName}"${constraint}${eol}`; + + const existing = content.match(entryRegex); + if (existing) { + return content.replace(existing[0], line); + } + + const sep = content.length === 0 || content.endsWith("\n") ? "" : eol; + return `${content}${sep}${line}`; +} diff --git a/src/engines/mutators/elixir.ts b/src/engines/mutators/elixir.ts new file mode 100644 index 0000000..f1b2776 --- /dev/null +++ b/src/engines/mutators/elixir.ts @@ -0,0 +1,111 @@ +import type { PackageSpec } from "../../types.js"; +import { cleanVersionSpec, escapeRegex } from "./file-helpers.js"; + +/** + * Safely mutates Elixir `mix.exs` inside `defp deps do [ ... ] end`. + */ +export function mutateMixExs(content: string, action: "add" | "remove", pkg: PackageSpec): string { + const pkgEsc = escapeRegex(pkg.name); + const entryRegex = new RegExp( + `^[ \\t]*\\{:${pkgEsc},\\s*["']([^"']+)["'][^\\r\\n]*\\},?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(entryRegex, ""); + } + + const rawVer = cleanVersionSpec(pkg.version); + const constraint = rawVer ? `~> ${rawVer}` : ">= 0.0.0"; + const existing = content.match(entryRegex); + if (existing) { + const updated = existing[0].replace( + new RegExp(`(\\{:${pkgEsc},\\s*["'])([^"']+)(["'])`), + `$1${constraint}$3`, + ); + return content.replace(existing[0], updated); + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const devOpt = pkg.isDev ? ", only: [:dev, :test]" : ""; + const entryBody = `{:${pkg.name}, "${constraint}"${devOpt}}`; + + const depsBlockRegex = /(defp\s+deps\s+do\s*\r?\n([ \t]*)\[)([\s\S]*?)(\r?\n\2\])/; + const match = content.match(depsBlockRegex); + if (match) { + const listIndent = match[2]; + const itemIndent = `${listIndent} `; + const inner = match[3]; + if (inner.trim().length === 0) { + return content.replace(match[0], `${match[1]}${eol}${itemIndent}${entryBody}${match[4]}`); + } + const withoutTrailing = inner.replace(/\s+$/, ""); + const needsComma = !withoutTrailing.endsWith(","); + const updatedInner = `${withoutTrailing}${needsComma ? "," : ""}${eol}${itemIndent}${entryBody}`; + return content.replace(match[0], `${match[1]}${updatedInner}${match[4]}`); + } + + const inlineEmptyMatch = content.match(/(defp\s+deps\s+do\s*\r?\n([ \t]*))\[\s*\]/); + if (inlineEmptyMatch) { + const listIndent = inlineEmptyMatch[2]; + const itemIndent = `${listIndent} `; + return content.replace( + inlineEmptyMatch[0], + `${inlineEmptyMatch[1]}[${eol}${itemIndent}${entryBody}${eol}${listIndent}]`, + ); + } + + return content; +} + +/** + * Safely mutates Erlang `rebar.config` `{deps, [ ... ]}.`. + */ +export function mutateRebarConfig( + content: string, + action: "add" | "remove", + pkg: PackageSpec, +): string { + const pkgEsc = escapeRegex(pkg.name); + const tupleRegex = new RegExp( + `^[ \\t]*(?:\\{${pkgEsc},\\s*["']([^"']+)["']\\}|${pkgEsc}),?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(tupleRegex, ""); + } + + const rawVer = cleanVersionSpec(pkg.version); + const newItem = rawVer ? `{${pkg.name}, "${rawVer}"}` : pkg.name; + + const existing = content.match(tupleRegex); + if (existing && rawVer) { + const hasComma = existing[0].trimEnd().endsWith(","); + const indent = existing[0].match(/^[ \t]*/)?.[0] ?? " "; + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + return content.replace(existing[0], `${indent}${newItem}${hasComma ? "," : ""}${eol}`); + } + if (existing) { + return content; + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const depsMatch = content.match(/(\{deps,\s*\[)([\s\S]*?)(\]\}\s*\.)/); + if (depsMatch) { + const inner = depsMatch[2]; + if (inner.trim().length === 0) { + return content.replace( + depsMatch[0], + `${depsMatch[1]}${eol} ${newItem}${eol}${depsMatch[3]}`, + ); + } + const stripped = inner.replace(/\s+$/, ""); + const needsComma = !stripped.endsWith(","); + const updated = `${depsMatch[1]}${stripped}${needsComma ? "," : ""}${eol} ${newItem}${eol}${depsMatch[3]}`; + return content.replace(depsMatch[0], updated); + } + + const sep = content.length === 0 || content.endsWith("\n") ? "" : eol; + return `${content}${sep}{deps, [${eol} ${newItem}${eol}]}.${eol}`; +} diff --git a/src/engines/mutators/file-helpers.ts b/src/engines/mutators/file-helpers.ts new file mode 100644 index 0000000..bb8c3e2 --- /dev/null +++ b/src/engines/mutators/file-helpers.ts @@ -0,0 +1,40 @@ +import fs from "node:fs"; +import path from "node:path"; + +export interface ManifestMutationResult { + manifestFile: string; + changed: boolean; +} + +/** + * Resolves the first existing manifest candidate inside cwd, reads it safely, + * runs a pure string transform, and writes back only when content changes. + */ +export function applyManifestTransform( + cwd: string, + candidates: readonly string[], + transform: (content: string, resolvedPath: string) => string, +): ManifestMutationResult | null { + for (const rel of candidates) { + if (!rel || rel.includes("*") || rel.includes("?")) continue; + const fullPath = path.join(cwd, rel); + if (!fs.existsSync(fullPath)) continue; + + const current = fs.readFileSync(fullPath, "utf-8"); + const next = transform(current, fullPath); + const changed = next !== current; + if (changed) { + fs.writeFileSync(fullPath, next, "utf-8"); + } + return { manifestFile: rel, changed }; + } + return null; +} + +export function escapeRegex(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +export function cleanVersionSpec(version?: string): string | undefined { + return version?.replace(/^[~^>=<\s]+/, "").trim() || undefined; +} diff --git a/src/engines/mutators/jvm.ts b/src/engines/mutators/jvm.ts new file mode 100644 index 0000000..aebcbd8 --- /dev/null +++ b/src/engines/mutators/jvm.ts @@ -0,0 +1,328 @@ +import type { PackageSpec } from "../../types.js"; +import { cleanVersionSpec, escapeRegex } from "./file-helpers.js"; + +export interface MavenCoordinates { + groupId: string; + artifactId: string; + version?: string; +} + +/** + * Normalizes Maven/Gradle/sbt coordinates from `group:artifact`, `group/artifact`, or `namespace/name`. + */ +export function parseJvmCoordinates(pkg: PackageSpec): MavenCoordinates { + const version = cleanVersionSpec(pkg.version); + if (pkg.namespace) { + return { + groupId: pkg.namespace.replace(/^@/, ""), + artifactId: pkg.name, + version, + }; + } + if (pkg.name.includes(":")) { + const [groupId, artifactId] = pkg.name.split(":", 2); + return { groupId: groupId.trim(), artifactId: artifactId.trim(), version }; + } + if (pkg.name.includes("/")) { + const [groupId, artifactId] = pkg.name.split("/", 2); + return { groupId: groupId.trim(), artifactId: artifactId.trim(), version }; + } + return { groupId: "org.example", artifactId: pkg.name.trim(), version }; +} + +/** + * Safely mutates a Maven pom.xml manifest (add/upsert or remove `` block). + */ +export function mutatePomXml(content: string, action: "add" | "remove", pkg: PackageSpec): string { + const { groupId, artifactId, version } = parseJvmCoordinates(pkg); + const gEsc = escapeRegex(groupId); + const aEsc = escapeRegex(artifactId); + + const depBlockRegex = new RegExp( + `[ \\t]*\\s*${gEsc}\\s*${aEsc}[\\s\\S]*?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(depBlockRegex, ""); + } + + const verLine = version ?? "RELEASE"; + const existing = content.match(depBlockRegex); + if (existing) { + const versionTagRegex = /()([^<]*)(<\/version>)/; + if (versionTagRegex.test(existing[0])) { + const updatedBlock = existing[0].replace(versionTagRegex, `$1${verLine}$3`); + return content.replace(existing[0], updatedBlock); + } + return content; + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const scopeTag = pkg.isDev ? `${eol} test` : ""; + + const depsCloseMatch = content.match(/^([ \t]*)<\/dependencies>/m); + if (depsCloseMatch) { + const baseIndent = depsCloseMatch[1]; + const depIndent = `${baseIndent} `; + const propIndent = `${depIndent} `; + const scopeLine = pkg.isDev ? `${eol}${propIndent}test` : ""; + const block = + `${depIndent}${eol}` + + `${propIndent}${groupId}${eol}` + + `${propIndent}${artifactId}${eol}` + + `${propIndent}${verLine}${scopeLine}${eol}` + + `${depIndent}${eol}`; + + return content.replace(depsCloseMatch[0], `${block}${depsCloseMatch[0]}`); + } + + const projectCloseMatch = content.match(/^([ \t]*)<\/project>/m); + if (projectCloseMatch) { + const baseIndent = `${projectCloseMatch[1]} `; + const depIndent = `${baseIndent} `; + const propIndent = `${depIndent} `; + const block = + `${baseIndent}${eol}` + + `${depIndent}${eol}` + + `${propIndent}${groupId}${eol}` + + `${propIndent}${artifactId}${eol}` + + `${propIndent}${verLine}${scopeTag}${eol}` + + `${depIndent}${eol}` + + `${baseIndent}${eol}`; + return content.replace(projectCloseMatch[0], `${block}${projectCloseMatch[0]}`); + } + + return content; +} + +/** + * Safely mutates an Apache Ivy `ivy.xml` manifest. + */ +export function mutateIvyXml(content: string, action: "add" | "remove", pkg: PackageSpec): string { + const { groupId, artifactId, version } = parseJvmCoordinates(pkg); + const gEsc = escapeRegex(groupId); + const aEsc = escapeRegex(artifactId); + + const tagRegex = new RegExp( + `[ \\t]*]*org=["']${gEsc}["'][^>]*name=["']${aEsc}["'][^>]*/?>\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(tagRegex, ""); + } + + const ver = version ?? "latest.release"; + const existing = content.match(tagRegex); + if (existing) { + const updatedTag = existing[0].replace(/(\brev=["'])([^"']*)(["'])/, `$1${ver}$3`); + return content.replace(existing[0], updatedTag); + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const closeMatch = content.match(/^([ \t]*)<\/dependencies>/m); + if (closeMatch) { + const indent = `${closeMatch[1]} `; + const conf = pkg.isDev ? ' conf="test->default"' : ""; + const tag = `${indent}${eol}`; + return content.replace(closeMatch[0], `${tag}${closeMatch[0]}`); + } + + return content; +} + +function toCatalogAlias(artifactId: string): string { + return artifactId.replace(/[^a-zA-Z0-9-]+/g, "-").toLowerCase(); +} + +/** + * Safely mutates Gradle Version Catalog (`gradle/libs.versions.toml`). + */ +export function mutateGradleCatalog( + content: string, + action: "add" | "remove", + pkg: PackageSpec, +): string { + const { groupId, artifactId, version } = parseJvmCoordinates(pkg); + const alias = toCatalogAlias(artifactId); + const gEsc = escapeRegex(groupId); + const aEsc = escapeRegex(artifactId); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + + const libLineRegex = new RegExp( + `^([a-zA-Z0-9_-]+)\\s*=\\s*\\{[^\\r\\n]*(?:module\\s*=\\s*["']${gEsc}:${aEsc}["']|group\\s*=\\s*["']${gEsc}["'][^\\r\\n]*name\\s*=\\s*["']${aEsc}["'])[^\\r\\n]*\\}\\r?\\n?`, + "m", + ); + + const match = content.match(libLineRegex); + if (action === "remove") { + if (!match) return content; + const matchedLine = match[0]; + const verRefMatch = matchedLine.match(/version\.ref\s*=\s*["']([^"']+)["']/); + let next = content.replace(matchedLine, ""); + if (verRefMatch?.[1]) { + const refEsc = escapeRegex(verRefMatch[1]); + if (!new RegExp(`version\\.ref\\s*=\\s*["']${refEsc}["']`).test(next)) { + next = next.replace(new RegExp(`^${refEsc}\\s*=\\s*["'][^"']*["']\\r?\\n?`, "m"), ""); + } + } + return next; + } + + const ver = version ?? "latest"; + if (match) { + const matchedLine = match[0]; + const verRefMatch = matchedLine.match(/version\.ref\s*=\s*["']([^"']+)["']/); + if (verRefMatch?.[1]) { + const refEsc = escapeRegex(verRefMatch[1]); + return content.replace( + new RegExp(`^(${refEsc}\\s*=\\s*["'])([^"']*)(["'])`, "m"), + `$1${ver}$3`, + ); + } + const directVerMatch = matchedLine.match(/(\bversion\s*=\s*["'])([^"']*)(["'])/); + if (directVerMatch) { + return content.replace(matchedLine, matchedLine.replace(directVerMatch[0], `$1${ver}$3`)); + } + return content; + } + + let next = content; + const verKey = alias; + if (/^\[versions\]/m.test(next)) { + const verPropRegex = new RegExp(`^(${escapeRegex(verKey)}\\s*=\\s*["'])([^"']*)(["'])`, "m"); + if (verPropRegex.test(next)) { + next = next.replace(verPropRegex, `$1${ver}$3`); + } else { + next = next.replace( + /^\[versions\][ \t]*\r?\n?/m, + (hdr) => `${hdr}${verKey} = "${ver}"${eol}`, + ); + } + } else { + next = `[versions]${eol}${verKey} = "${ver}"${eol}${eol}${next}`; + } + + const libEntry = `${alias} = { group = "${groupId}", name = "${artifactId}", version.ref = "${verKey}" }${eol}`; + if (/^\[libraries\]/m.test(next)) { + next = next.replace(/^\[libraries\][ \t]*\r?\n?/m, (hdr) => `${hdr}${libEntry}`); + } else { + const sep = next.endsWith("\n") ? eol : `${eol}${eol}`; + next = `${next}${sep}[libraries]${eol}${libEntry}`; + } + + return next; +} + +/** + * Safely mutates `build.gradle` (Groovy) or `build.gradle.kts` (Kotlin DSL). + */ +export function mutateGradleBuild( + content: string, + action: "add" | "remove", + pkg: PackageSpec, + isKotlinDsl = false, +): string { + const { groupId, artifactId, version } = parseJvmCoordinates(pkg); + const coordPrefixEsc = escapeRegex(`${groupId}:${artifactId}`); + + const depRegex = new RegExp( + `^[ \\t]*(?:testImplementation|implementation|api|compileOnly|runtimeOnly)\\s*(?:\\(\\s*)?["']${coordPrefixEsc}(?::([^"']*))?["']\\s*\\)?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(depRegex, ""); + } + + const ver = version ?? "latest.release"; + const existing = content.match(depRegex); + if (existing) { + const updatedLine = existing[0].replace( + new RegExp(`(["'])${coordPrefixEsc}(?::[^"']*)?(["'])`), + `$1${groupId}:${artifactId}:${ver}$2`, + ); + return content.replace(existing[0], updatedLine); + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const cfg = pkg.isDev ? "testImplementation" : "implementation"; + const lineBody = isKotlinDsl + ? `${cfg}("${groupId}:${artifactId}:${ver}")` + : `${cfg} '${groupId}:${artifactId}:${ver}'`; + + const depsBlockRegex = /^([ \t]*)dependencies\s*\{[\s\S]*?^\1\}/m; + const blockMatch = content.match(depsBlockRegex); + if (blockMatch) { + const blockIndent = blockMatch[1]; + const itemIndent = `${blockIndent} `; + const closeToken = `${blockIndent}}`; + const lastIdx = blockMatch[0].lastIndexOf(closeToken); + if (lastIdx !== -1) { + const updatedBlock = + `${blockMatch[0].slice(0, lastIdx)}` + + `${itemIndent}${lineBody}${eol}` + + `${blockMatch[0].slice(lastIdx)}`; + return content.replace(blockMatch[0], updatedBlock); + } + } + + const prefix = content.endsWith("\n") ? eol : `${eol}${eol}`; + return `${content}${prefix}dependencies {${eol} ${lineBody}${eol}}${eol}`; +} + +/** + * Safely mutates Scala sbt `build.sbt`. + */ +export function mutateSbtBuild( + content: string, + action: "add" | "remove", + pkg: PackageSpec, +): string { + const { groupId, artifactId, version } = parseJvmCoordinates(pkg); + const gEsc = escapeRegex(groupId); + const aEsc = escapeRegex(artifactId); + + const singleLineRegex = new RegExp( + `^[ \\t]*libraryDependencies\\s*\\+=\\s*["']${gEsc}["']\\s*%{1,2}\\s*["']${aEsc}["']\\s*%\\s*["']([^"']+)["'](?:\\s*%\\s*Test)?\\r?\\n?`, + "m", + ); + const tupleEntryRegex = new RegExp( + `^[ \\t]*["']${gEsc}["']\\s*%{1,2}\\s*["']${aEsc}["']\\s*%\\s*["']([^"']+)["'](?:\\s*%\\s*Test)?,?\\r?\\n?`, + "m", + ); + + if (action === "remove") { + return content.replace(singleLineRegex, "").replace(tupleEntryRegex, ""); + } + + const ver = version ?? "latest.integration"; + const verReplaceRegex = new RegExp(`(["']${aEsc}["']\\s*%\\s*["'])([^"']+)(["'])`); + const singleExisting = content.match(singleLineRegex); + if (singleExisting) { + const updated = singleExisting[0].replace(verReplaceRegex, `$1${ver}$3`); + return content.replace(singleExisting[0], updated); + } + + const tupleExisting = content.match(tupleEntryRegex); + if (tupleExisting) { + const updated = tupleExisting[0].replace(verReplaceRegex, `$1${ver}$3`); + return content.replace(tupleExisting[0], updated); + } + + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const testSuffix = pkg.isDev ? " % Test" : ""; + const seqMatch = content.match(/libraryDependencies\s*\+\+=\s*Seq\s*\(([\s\S]*?)\)/); + if (seqMatch) { + const inner = seqMatch[1]; + const hasItems = inner.trim().length > 0; + const normalizedInner = hasItems ? `${inner.replace(/[,\s]+$/, "")},${eol}` : eol; + const entry = ` "${groupId}" %% "${artifactId}" % "${ver}"${testSuffix}${eol}`; + return content.replace(seqMatch[0], `libraryDependencies ++= Seq(${normalizedInner}${entry})`); + } + + const newLine = `libraryDependencies += "${groupId}" %% "${artifactId}" % "${ver}"${testSuffix}${eol}`; + const sep = content.length === 0 || content.endsWith("\n") ? "" : eol; + return `${content}${sep}${newLine}`; +} diff --git a/src/engines/registry.ts b/src/engines/registry.ts index d931357..ee0d0a8 100644 --- a/src/engines/registry.ts +++ b/src/engines/registry.ts @@ -8,6 +8,7 @@ import { GoEngine } from "./go.js"; import { NodeEngine } from "./node.js"; import { PythonEngine } from "./python.js"; import { RustEngine } from "./rust.js"; +import { TIER2_MANIFEST_ADAPTERS } from "./tier2-manifest.js"; /** * Central extensible EngineAdapter registry powering detection, PURL parsing, @@ -294,6 +295,9 @@ for (const adapter of BACKEND_MOBILE_ADAPTERS) { for (const adapter of CPP_JULIA_ADAPTERS) { engineRegistry.register(adapter); } +for (const adapter of TIER2_MANIFEST_ADAPTERS) { + engineRegistry.register(adapter); +} /** Ensures a PackageSpec target cleanly detects its first existing manifest file in cwd if missing. */ export function resolveEcosystemLockContext(ecosystem: Ecosystem, cwd: string): EngineContext { diff --git a/src/engines/tier2-manifest.ts b/src/engines/tier2-manifest.ts new file mode 100644 index 0000000..4c88fc7 --- /dev/null +++ b/src/engines/tier2-manifest.ts @@ -0,0 +1,323 @@ +import fs from "node:fs"; +import path from "node:path"; +import type { EngineContext, PackageSpec } from "../types.js"; +import { type EngineAdapter, defineDeclarativeAdapter } from "./declarative.js"; +import { + mutateCartfile, + mutatePackageSwift, + mutatePodfile, + normalizeSwiftPackageSpec, +} from "./mutators/apple.js"; +import { mutateMixExs, mutateRebarConfig } from "./mutators/elixir.js"; +import { applyManifestTransform } from "./mutators/file-helpers.js"; +import { + mutateGradleBuild, + mutateGradleCatalog, + mutateIvyXml, + mutatePomXml, + mutateSbtBuild, + parseJvmCoordinates, +} from "./mutators/jvm.js"; + +function isIvyProject(ctx?: EngineContext): boolean { + return ctx?.preferredCli === "ant" || ctx?.manifest === "ivy.xml"; +} + +function getMavenBinary(ctx?: EngineContext): string { + if ( + ctx?.cwd && + fs.existsSync(path.join(ctx.cwd, process.platform === "win32" ? "mvnw.cmd" : "mvnw")) + ) { + return process.platform === "win32" ? "mvnw.cmd" : "./mvnw"; + } + return "mvn"; +} + +function getGradleBinary(ctx?: EngineContext): string { + if ( + ctx?.cwd && + fs.existsSync(path.join(ctx.cwd, process.platform === "win32" ? "gradlew.bat" : "gradlew")) + ) { + return process.platform === "win32" ? "gradlew.bat" : "./gradlew"; + } + return "gradle"; +} + +/** Java / JVM — Maven (pom.xml) & Apache Ivy (ivy.xml) */ +export const mavenAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "maven", + ecosystem: "maven", + aliases: ["mvn", "java", "jvm", "ivy"], + purlTypes: ["maven"], + manifests: ["pom.xml", "ivy.xml"], + lockfiles: [], + osvEcosystem: "Maven", + sbomPurlType: "maven", + supportedClis: ["mvn", "ant"], + commands: { + command: (ctx) => (isIvyProject(ctx) ? "ant" : getMavenBinary(ctx)), + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "pom.xml", "ivy.xml"], (content, full) => + full.endsWith("ivy.xml") + ? mutateIvyXml(content, "add", pkg) + : mutatePomXml(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "pom.xml", "ivy.xml"], (content, full) => + full.endsWith("ivy.xml") + ? mutateIvyXml(content, "remove", pkg) + : mutatePomXml(content, "remove", pkg), + ), + add: (_pkg, ctx) => (isIvyProject(ctx) ? ["resolve"] : ["dependency:resolve"]), + remove: (_pkg, ctx) => (isIvyProject(ctx) ? ["resolve"] : ["dependency:resolve"]), + install: (ctx) => (isIvyProject(ctx) ? ["resolve"] : ["dependency:resolve"]), + update: (pkg, ctx) => { + if (isIvyProject(ctx)) return ["resolve"]; + if (pkg) { + const { groupId, artifactId } = parseJvmCoordinates(pkg); + return ["versions:use-latest-versions", `-Dincludes=${groupId}:${artifactId}`]; + } + return ["versions:use-latest-releases"]; + }, + }, + resolveScriptCommand: (script) => + script === "test" ? ["mvn", ["test"]] : ["mvn", ["package", "-DskipTests"]], + injectRegistryEnv: (endpoint, env) => { + env.MAVEN_ARGS = `-Dmaven.repo.remote=${endpoint.url}`; + }, +}); + +/** Java / Kotlin — Gradle (gradle/libs.versions.toml Version Catalogs + build.gradle(.kts)) */ +export const gradleAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "gradle", + ecosystem: "gradle", + aliases: ["kts", "kotlin"], + purlTypes: ["gradle"], + manifests: ["build.gradle.kts", "build.gradle", "gradle/libs.versions.toml"], + lockfiles: ["gradle.lockfile"], + osvEcosystem: "Maven", + sbomPurlType: "maven", + supportedClis: ["gradle"], + commands: { + command: (ctx) => getGradleBinary(ctx), + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform( + cwd, + [ctx?.manifest ?? "", "gradle/libs.versions.toml", "build.gradle.kts", "build.gradle"], + (content, full) => { + if (full.endsWith("libs.versions.toml")) { + return mutateGradleCatalog(content, "add", pkg); + } + return mutateGradleBuild(content, "add", pkg, full.endsWith(".kts")); + }, + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform( + cwd, + [ctx?.manifest ?? "", "gradle/libs.versions.toml", "build.gradle.kts", "build.gradle"], + (content, full) => { + if (full.endsWith("libs.versions.toml")) { + return mutateGradleCatalog(content, "remove", pkg); + } + return mutateGradleBuild(content, "remove", pkg, full.endsWith(".kts")); + }, + ), + add: () => ["dependencies", "--refresh-dependencies"], + remove: () => ["--refresh-dependencies"], + install: () => ["--refresh-dependencies"], + update: () => ["--refresh-dependencies"], + }, + resolveScriptCommand: (script) => + script === "test" ? ["gradle", ["test"]] : ["gradle", [script]], +}); + +/** Scala / JVM — sbt (build.sbt) */ +export const sbtAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "sbt", + ecosystem: "sbt", + aliases: ["scala"], + purlTypes: ["sbt"], + manifests: ["build.sbt"], + lockfiles: [], + osvEcosystem: "Maven", + sbomPurlType: "maven", + supportedClis: ["sbt"], + commands: { + command: "sbt", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "build.sbt"], (content) => + mutateSbtBuild(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "build.sbt"], (content) => + mutateSbtBuild(content, "remove", pkg), + ), + add: () => ["update"], + remove: () => ["update"], + install: () => ["update"], + update: () => ["update"], + }, + resolveScriptCommand: (script) => (script === "test" ? ["sbt", ["test"]] : ["sbt", [script]]), +}); + +/** Elixir — Mix / Hex (mix.exs + mix.lock) */ +export const hexAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "mix", + ecosystem: "hex", + aliases: ["elixir", "mix"], + purlTypes: ["hex"], + manifests: ["mix.exs"], + lockfiles: ["mix.lock"], + osvEcosystem: "Hex", + sbomPurlType: "hex", + supportedClis: ["mix"], + commands: { + command: "mix", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "mix.exs"], (content) => + mutateMixExs(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "mix.exs"], (content) => + mutateMixExs(content, "remove", pkg), + ), + add: () => ["deps.get"], + remove: (pkg) => ["deps.clean", pkg.name, "--unlock"], + install: () => ["deps.get"], + update: (pkg) => (pkg ? ["deps.update", pkg.name] : ["deps.update", "--all"]), + }, + resolveScriptCommand: (script) => ["mix", [script]], + injectRegistryEnv: (endpoint, env) => { + env.HEX_MIRROR = endpoint.url; + }, +}); + +/** Erlang — Rebar3 (rebar.config + rebar.lock) */ +export const rebar3Adapter: EngineAdapter = defineDeclarativeAdapter({ + id: "rebar3", + ecosystem: "rebar3", + aliases: ["erlang", "rebar"], + purlTypes: ["rebar3"], + manifests: ["rebar.config"], + lockfiles: ["rebar.lock"], + osvEcosystem: "Hex", + sbomPurlType: "hex", + supportedClis: ["rebar3"], + commands: { + command: "rebar3", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "rebar.config"], (content) => + mutateRebarConfig(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "rebar.config"], (content) => + mutateRebarConfig(content, "remove", pkg), + ), + add: () => ["get-deps"], + remove: () => ["unlock"], + install: () => ["get-deps"], + update: (pkg) => (pkg ? ["upgrade", pkg.name] : ["upgrade"]), + }, + resolveScriptCommand: (script) => + script === "test" ? ["rebar3", ["eunit"]] : ["rebar3", [script]], +}); + +/** Apple / Swift — Swift Package Manager (Package.swift + Package.resolved) */ +export const swiftAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "swift", + ecosystem: "swift", + aliases: ["spm", "swiftpm"], + purlTypes: ["swift"], + manifests: ["Package.swift"], + lockfiles: ["Package.resolved"], + osvEcosystem: "SwiftURL", + sbomPurlType: "swift", + supportedClis: ["swift"], + commands: { + command: "swift", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Package.swift"], (content) => + mutatePackageSwift(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Package.swift"], (content) => + mutatePackageSwift(content, "remove", pkg), + ), + add: () => ["package", "resolve"], + remove: () => ["package", "resolve"], + install: () => ["package", "resolve"], + update: (pkg) => + pkg + ? ["package", "update", normalizeSwiftPackageSpec(pkg).packageName] + : ["package", "update"], + }, + resolveScriptCommand: (script) => + script === "test" ? ["swift", ["test"]] : ["swift", ["build"]], +}); + +/** Apple / iOS / macOS — CocoaPods (Podfile + Podfile.lock) */ +export const cocoapodsAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "cocoapods", + ecosystem: "cocoapods", + aliases: ["pod", "pods"], + purlTypes: ["cocoapods"], + manifests: ["Podfile", "*.podspec"], + lockfiles: ["Podfile.lock"], + osvEcosystem: undefined, + sbomPurlType: "cocoapods", + supportedClis: ["pod"], + commands: { + command: "pod", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Podfile"], (content) => + mutatePodfile(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Podfile"], (content) => + mutatePodfile(content, "remove", pkg), + ), + add: () => ["install"], + remove: () => ["install"], + install: () => ["install"], + update: (pkg) => (pkg ? ["update", pkg.name] : ["update"]), + }, +}); + +/** Apple / iOS — Carthage (Cartfile + Cartfile.resolved) */ +export const carthageAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "carthage", + ecosystem: "carthage", + aliases: [], + purlTypes: ["carthage"], + manifests: ["Cartfile"], + lockfiles: ["Cartfile.resolved"], + osvEcosystem: undefined, + sbomPurlType: "github", + supportedClis: ["carthage"], + commands: { + command: "carthage", + mutateAdd: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Cartfile"], (content) => + mutateCartfile(content, "add", pkg), + ), + mutateRemove: (pkg, cwd, ctx) => + applyManifestTransform(cwd, [ctx?.manifest ?? "", "Cartfile"], (content) => + mutateCartfile(content, "remove", pkg), + ), + add: () => ["bootstrap"], + remove: () => ["update"], + install: () => ["bootstrap"], + update: (pkg) => (pkg ? ["update", pkg.name] : ["update"]), + }, +}); + +export const TIER2_MANIFEST_ADAPTERS: readonly EngineAdapter[] = [ + mavenAdapter, + gradleAdapter, + sbtAdapter, + hexAdapter, + rebar3Adapter, + swiftAdapter, + cocoapodsAdapter, + carthageAdapter, +]; diff --git a/src/outdated/checker.ts b/src/outdated/checker.ts index 213e409..b98c73a 100644 --- a/src/outdated/checker.ts +++ b/src/outdated/checker.ts @@ -2,7 +2,10 @@ import fs from "node:fs"; import path from "node:path"; import type { Ecosystem } from "../types.js"; import { resolveWorkspaceMembers } from "../workspace/config.js"; -import { extractBackendMobileDependencies } from "../workspace/crypto.js"; +import { + extractBackendMobileDependencies, + extractTier2ManifestDependencies, +} from "../workspace/crypto.js"; import { compareSemver } from "./semver.js"; import type { OutdatedDependency, OutdatedScanReport } from "./types.js"; @@ -250,6 +253,135 @@ async function fetchPubLatest(name: string): Promise { } } +async function fetchMavenLatest(name: string): Promise { + const normalized = name.includes("/") ? name.replace("/", ":") : name; + const cacheKey = `maven:${normalized}`; + if (REGISTRY_CACHE.has(cacheKey)) return REGISTRY_CACHE.get(cacheKey) || null; + + const [groupId, artifactId] = normalized.split(":", 2); + if (!groupId || !artifactId) return null; + + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + const url = `https://search.maven.org/solrsearch/select?q=g:${encodeURIComponent(groupId)}+AND+a:${encodeURIComponent(artifactId)}&core=gav&rows=20&wt=json`; + const res = await fetch(url, { signal: controller.signal }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { response?: { docs?: Array<{ v?: string }> } }; + const versions = (data.response?.docs ?? []) + .map((d) => d.v) + .filter((v): v is string => Boolean(v)); + const latest = + versions.find((v) => !/-(?:alpha|beta|rc|m\d+|snapshot)/i.test(v)) ?? versions[0] ?? null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchHexLatest(name: string): Promise { + const cacheKey = `hex:${name}`; + if (REGISTRY_CACHE.has(cacheKey)) return REGISTRY_CACHE.get(cacheKey) || null; + + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + const res = await fetch(`https://hex.pm/api/packages/${encodeURIComponent(name)}`, { + signal: controller.signal, + }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { + releases?: Array<{ version?: string }>; + latest_stable_version?: string; + }; + const latest = + data.latest_stable_version ?? + data.releases?.find((r) => r.version && !r.version.includes("-"))?.version ?? + data.releases?.[0]?.version ?? + null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchCocoaPodsLatest(name: string): Promise { + const cacheKey = `cocoapods:${name}`; + if (REGISTRY_CACHE.has(cacheKey)) return REGISTRY_CACHE.get(cacheKey) || null; + + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + const res = await fetch(`https://trunk.cocoapods.org/api/v1/pods/${encodeURIComponent(name)}`, { + signal: controller.signal, + }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { versions?: Array<{ name?: string }> }; + const versions = (data.versions ?? []) + .map((v) => v.name) + .filter((v): v is string => Boolean(v)); + const latest = versions[versions.length - 1] ?? null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchSwiftLatest(name: string): Promise { + const stripped = name + .replace(/^https?:\/\//i, "") + .replace(/^github\.com\//i, "") + .replace(/\.git$/i, ""); + const [owner, repo] = stripped.split("/", 2); + if (!owner || !repo) return null; + + const cacheKey = `swift:${owner}/${repo}`; + if (REGISTRY_CACHE.has(cacheKey)) return REGISTRY_CACHE.get(cacheKey) || null; + + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/tags`, { + signal: controller.signal, + headers: { + Accept: "application/vnd.github+json", + "User-Agent": "poly-cli/0.6.2 (developer@ritualdev.in)", + }, + }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const tags = (await res.json()) as Array<{ name?: string }>; + const tag = tags.find((t) => t.name && /^v?\d+\.\d+/.test(t.name))?.name ?? tags[0]?.name; + const latest = tag ? tag.replace(/^v/, "") : null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + /** * Dispatches to registry fetcher based on ecosystem. */ @@ -274,6 +406,18 @@ export async function fetchLatestVersion( return fetchGemLatest(name); case "pub": return fetchPubLatest(name); + case "maven": + case "gradle": + case "sbt": + return fetchMavenLatest(name); + case "hex": + case "rebar3": + return fetchHexLatest(name); + case "cocoapods": + return fetchCocoaPodsLatest(name); + case "swift": + case "carthage": + return fetchSwiftLatest(name); default: return null; } @@ -427,6 +571,25 @@ function extractDeclaredDependencies( } break; } + case "maven": + case "gradle": + case "sbt": + case "hex": + case "rebar3": + case "swift": + case "cocoapods": + case "carthage": { + for (const item of extractTier2ManifestDependencies(manifestPath, content, ecosystem)) { + if (item.version === "any" || item.version === "latest") continue; + deps.push({ + name: item.name, + version: item.version, + ecosystem: item.ecosystem, + memberPath, + }); + } + break; + } } return deps; diff --git a/src/outdated/upgrader.ts b/src/outdated/upgrader.ts index 4c7a250..3d11353 100644 --- a/src/outdated/upgrader.ts +++ b/src/outdated/upgrader.ts @@ -1,5 +1,15 @@ import fs from "node:fs"; import path from "node:path"; +import { mutateCartfile, mutatePackageSwift, mutatePodfile } from "../engines/mutators/apple.js"; +import { mutateMixExs, mutateRebarConfig } from "../engines/mutators/elixir.js"; +import { + mutateGradleBuild, + mutateGradleCatalog, + mutateIvyXml, + mutatePomXml, + mutateSbtBuild, +} from "../engines/mutators/jvm.js"; +import type { PackageSpec } from "../types.js"; import { resolveWorkspaceMembers } from "../workspace/config.js"; import { writeCompositeLockfile } from "../workspace/lockfile.js"; import { scanOutdatedDependencies } from "./checker.js"; @@ -118,6 +128,38 @@ export function patchManifestVersion( } } + // 4. Phase 4 Tier 2 manifests (JVM, Elixir/Erlang, Swift/Apple) + const cleanVer = newVersion.replace(/^[\^~><=v\s]+/, ""); + const spec: PackageSpec = { raw: pkgName, name: pkgName, version: cleanVer }; + let mutated = content; + + if (manifestPath.endsWith("pom.xml")) { + mutated = mutatePomXml(content, "add", spec); + } else if (manifestPath.endsWith("ivy.xml")) { + mutated = mutateIvyXml(content, "add", spec); + } else if (manifestPath.endsWith("libs.versions.toml")) { + mutated = mutateGradleCatalog(content, "add", spec); + } else if (manifestPath.endsWith("build.gradle.kts") || manifestPath.endsWith("build.gradle")) { + mutated = mutateGradleBuild(content, "add", spec, manifestPath.endsWith(".kts")); + } else if (manifestPath.endsWith("build.sbt")) { + mutated = mutateSbtBuild(content, "add", spec); + } else if (manifestPath.endsWith("mix.exs")) { + mutated = mutateMixExs(content, "add", spec); + } else if (manifestPath.endsWith("rebar.config")) { + mutated = mutateRebarConfig(content, "add", spec); + } else if (manifestPath.endsWith("Package.swift")) { + mutated = mutatePackageSwift(content, "add", spec); + } else if (manifestPath.endsWith("Podfile")) { + mutated = mutatePodfile(content, "add", spec); + } else if (manifestPath.endsWith("Cartfile")) { + mutated = mutateCartfile(content, "add", spec); + } + + if (mutated !== content) { + fs.writeFileSync(manifestPath, mutated, "utf-8"); + return true; + } + return false; } diff --git a/src/security/registry.ts b/src/security/registry.ts index 24795a4..d252a7f 100644 --- a/src/security/registry.ts +++ b/src/security/registry.ts @@ -314,6 +314,152 @@ export async function fetchRegistryMetadata( return meta; } + if (ecosystem === "maven" || ecosystem === "gradle" || ecosystem === "sbt") { + const normalized = packageName.includes("/") ? packageName.replace("/", ":") : packageName; + const [groupId, artifactId] = normalized.split(":", 2); + if (!groupId || !artifactId) { + clearTimeout(timer); + return null; + } + const url = `https://search.maven.org/solrsearch/select?q=g:${encodeURIComponent(groupId)}+AND+a:${encodeURIComponent(artifactId)}&core=gav&rows=20&wt=json`; + const res = await fetch(url, { + signal: controller.signal, + headers: { Accept: "application/json" }, + }); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + response?: { docs?: Array<{ v?: string; timestamp?: number }> }; + }; + const versions: Record = {}; + let latestVersion: string | undefined; + for (const doc of data.response?.docs ?? []) { + if (!doc.v) continue; + if (!latestVersion) latestVersion = doc.v; + versions[doc.v] = { + version: doc.v, + publishedAt: doc.timestamp ? new Date(doc.timestamp).toISOString() : undefined, + license: "APACHE-2.0", + }; + } + const meta: RegistryMetadata = { + name: normalized, + ecosystem, + latestVersion, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "hex" || ecosystem === "rebar3") { + const res = await fetch(`https://hex.pm/api/packages/${encodeURIComponent(packageName)}`, { + signal: controller.signal, + headers: { Accept: "application/json" }, + }); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + meta?: { licenses?: string[] }; + latest_stable_version?: string; + releases?: Array<{ version?: string; inserted_at?: string }>; + }; + const license = normalizeLicenseString(data.meta?.licenses?.[0]); + const versions: Record = {}; + for (const rel of data.releases ?? []) { + if (!rel.version) continue; + versions[rel.version] = { + version: rel.version, + publishedAt: rel.inserted_at, + license, + }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem, + latestVersion: data.latest_stable_version ?? data.releases?.[0]?.version, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "cocoapods") { + const res = await fetch( + `https://trunk.cocoapods.org/api/v1/pods/${encodeURIComponent(packageName)}`, + { signal: controller.signal, headers: { Accept: "application/json" } }, + ); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + versions?: Array<{ name?: string; created_at?: string }>; + }; + const versions: Record = {}; + let latestVersion: string | undefined; + for (const v of data.versions ?? []) { + if (!v.name) continue; + latestVersion = v.name; + versions[v.name] = { + version: v.name, + publishedAt: v.created_at, + license: "MIT", + }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem: "cocoapods", + latestVersion, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "swift" || ecosystem === "carthage") { + const stripped = packageName + .replace(/^https?:\/\//i, "") + .replace(/^github\.com\//i, "") + .replace(/\.git$/i, ""); + const [owner, repo] = stripped.split("/", 2); + if (!owner || !repo) { + clearTimeout(timer); + return null; + } + const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/tags`, { + signal: controller.signal, + headers: { + Accept: "application/vnd.github+json", + "User-Agent": "poly-firewall/0.6.2 (developer@ritualdev.in)", + }, + }); + clearTimeout(timer); + if (!res.ok) return null; + + const tags = (await res.json()) as Array<{ name?: string }>; + const versions: Record = {}; + let latestVersion: string | undefined; + for (const t of tags) { + if (!t.name) continue; + const clean = t.name.replace(/^v/, ""); + if (!latestVersion) latestVersion = clean; + versions[clean] = { + version: clean, + license: "UNKNOWN", + }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem, + latestVersion, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + clearTimeout(timer); return null; } catch { diff --git a/src/types.ts b/src/types.ts index e5b3522..563a315 100644 --- a/src/types.ts +++ b/src/types.ts @@ -17,7 +17,15 @@ export type BuiltinEcosystem = | "conan" | "vcpkg" | "meson" - | "julia"; + | "julia" + | "maven" + | "gradle" + | "sbt" + | "hex" + | "rebar3" + | "swift" + | "cocoapods" + | "carthage"; export type Ecosystem = BuiltinEcosystem | (string & {}); export interface EngineContext { diff --git a/src/workspace/crypto.ts b/src/workspace/crypto.ts index d3ccbaa..72f31ac 100644 --- a/src/workspace/crypto.ts +++ b/src/workspace/crypto.ts @@ -346,11 +346,206 @@ export function extractDirectDependencies(manifestPath: string, ecosystem: Ecosy } break; } + case "maven": + case "gradle": + case "sbt": + case "hex": + case "rebar3": + case "swift": + case "cocoapods": + case "carthage": { + for (const item of extractTier2ManifestDependencies(manifestPath, content, ecosystem)) { + deps.push(`${item.ecosystem}:${item.name}@${item.version}`); + } + break; + } } return deps.sort(); } +function parseGradleCatalogContent(catalogContent: string, deps: ParsedManifestDep[]): void { + const versions = new Map(); + let section = ""; + const rawLibraries: string[] = []; + + for (const rawLine of catalogContent.split(/\r?\n/)) { + const line = rawLine.replace(/#.*$/, "").trim(); + if (!line) continue; + const sec = line.match(/^\[([^\]]+)\]$/); + if (sec) { + section = sec[1]?.trim() ?? ""; + continue; + } + if (section === "versions") { + const kv = line.match(/^([a-zA-Z0-9_.-]+)\s*=\s*["']([^"']+)["']/); + if (kv?.[1] && kv[2]) versions.set(kv[1], kv[2].trim()); + } else if (section === "libraries") { + rawLibraries.push(line); + } + } + + for (const line of rawLibraries) { + const moduleMatch = line.match(/\bmodule\s*=\s*["']([^"':]+):([^"']+)["']/); + const groupMatch = line.match(/\bgroup\s*=\s*["']([^"']+)["']/); + const nameMatch = line.match(/\bname\s*=\s*["']([^"']+)["']/); + const groupId = moduleMatch?.[1] ?? groupMatch?.[1]; + const artifactId = moduleMatch?.[2] ?? nameMatch?.[1]; + if (!groupId || !artifactId) continue; + + const refMatch = line.match(/\bversion\.ref\s*=\s*["']([^"']+)["']/); + const directVerMatch = line.match(/\bversion\s*=\s*["']([^"']+)["']/); + const version = (refMatch?.[1] ? versions.get(refMatch[1]) : directVerMatch?.[1]) ?? "latest"; + deps.push({ ecosystem: "gradle", name: `${groupId}:${artifactId}`, version }); + } +} + +/** + * Extracts dependency name/version pairs for Phase 4 Tier 2 ecosystems + * (Maven/Ivy, Gradle/Version Catalog, sbt, Mix/Hex, Rebar3, SPM, CocoaPods, Carthage). + */ +export function extractTier2ManifestDependencies( + manifestPath: string, + content: string, + ecosystem: Ecosystem, +): ParsedManifestDep[] { + const deps: ParsedManifestDep[] = []; + const fileName = path.basename(manifestPath); + + if (ecosystem === "maven") { + if (fileName === "ivy.xml") { + for (const m of content.matchAll( + /]*org=["']([^"']+)["'][^>]*name=["']([^"']+)["'](?:\s+[^>]*rev=["']([^"']+)["'])?/gi, + )) { + if (m[1] && m[2]) { + deps.push({ + ecosystem: "maven", + name: `${m[1].trim()}:${m[2].trim()}`, + version: (m[3] || "latest").trim(), + }); + } + } + return deps; + } + for (const block of content.matchAll(/([\s\S]*?)<\/dependency>/gi)) { + const inner = block[1] ?? ""; + const g = inner.match(/\s*([^<\s]+)\s*<\/groupId>/i)?.[1]; + const a = inner.match(/\s*([^<\s]+)\s*<\/artifactId>/i)?.[1]; + const v = inner.match(/\s*([^<\s]+)\s*<\/version>/i)?.[1]; + if (g && a) { + deps.push({ ecosystem: "maven", name: `${g}:${a}`, version: v || "latest" }); + } + } + return deps; + } + + if (ecosystem === "gradle") { + if (fileName === "libs.versions.toml") { + parseGradleCatalogContent(content, deps); + return deps; + } + for (const m of content.matchAll( + /\b(?:implementation|api|testImplementation|compileOnly|runtimeOnly)\s*\(?\s*["']([^"':\s]+):([^"':\s]+)(?::([^"'\s]+))?["']/g, + )) { + if (m[1] && m[2]) { + deps.push({ + ecosystem: "gradle", + name: `${m[1]}:${m[2]}`, + version: m[3] || "latest", + }); + } + } + const siblingCatalog = path.join(path.dirname(manifestPath), "gradle", "libs.versions.toml"); + if (fs.existsSync(siblingCatalog)) { + parseGradleCatalogContent(fs.readFileSync(siblingCatalog, "utf-8"), deps); + } + return deps; + } + + if (ecosystem === "sbt") { + for (const m of content.matchAll( + /["']([^"']+)["']\s*%{1,2}\s*["']([^"']+)["']\s*%\s*["']([^"']+)["']/g, + )) { + if (m[1] && m[2]) { + deps.push({ ecosystem: "sbt", name: `${m[1]}:${m[2]}`, version: m[3] || "latest" }); + } + } + return deps; + } + + if (ecosystem === "hex") { + for (const m of content.matchAll(/\{:([a-zA-Z0-9_]+),\s*["']([^"']+)["']/g)) { + if (m[1]) { + deps.push({ + ecosystem: "hex", + name: m[1], + version: m[2]?.replace(/^[~>=<\s]+/, "").trim() || "latest", + }); + } + } + return deps; + } + + if (ecosystem === "rebar3") { + const block = content.match(/\{deps,\s*\[([\s\S]*?)\]\}\s*\./); + const body = block?.[1] ?? content; + for (const m of body.matchAll(/\{([a-zA-Z0-9_]+),\s*["']([^"']+)["']\}/g)) { + if (m[1]) { + deps.push({ ecosystem: "rebar3", name: m[1], version: m[2]?.trim() || "latest" }); + } + } + return deps; + } + + if (ecosystem === "swift") { + for (const m of content.matchAll( + /\.package\(\s*url:\s*["']([^"']+)["'](?:\s*,\s*(?:from|exact)\s*:\s*["']([^"']+)["'])?/g, + )) { + if (m[1]) { + const canonical = m[1].replace(/^https?:\/\//i, "").replace(/\.git$/i, ""); + deps.push({ + ecosystem: "swift", + name: canonical, + version: m[2]?.trim() || "latest", + }); + } + } + return deps; + } + + if (ecosystem === "cocoapods") { + for (const rawLine of content.split(/\r?\n/)) { + const m = rawLine.trim().match(/^pod\s+["']([^"']+)["'](?:\s*,\s*["']([^"']+)["'])?/); + if (m?.[1]) { + deps.push({ + ecosystem: "cocoapods", + name: m[1], + version: m[2]?.replace(/^[~>=<\s]+/, "").trim() || "latest", + }); + } + } + return deps; + } + + if (ecosystem === "carthage") { + for (const rawLine of content.split(/\r?\n/)) { + const m = rawLine + .trim() + .match(/^(?:github|git|binary)\s+["']([^"']+)["'](?:\s+(?:~>|==|>=)\s*([^\s#]+))?/); + if (m?.[1]) { + deps.push({ + ecosystem: "carthage", + name: m[1], + version: m[2]?.trim() || "latest", + }); + } + } + return deps; + } + + return deps; +} + function extractCppJuliaDependencies( manifestPath: string, content: string, diff --git a/tests/completion.test.ts b/tests/completion.test.ts index 148827f..d6e931b 100644 --- a/tests/completion.test.ts +++ b/tests/completion.test.ts @@ -55,6 +55,14 @@ test("Shell Auto-Completion - Dynamic Resolution", async (t) => { "vcpkg", "meson", "julia", + "maven", + "gradle", + "sbt", + "hex", + "rebar3", + "swift", + "cocoapods", + "carthage", ]); }); diff --git a/tests/phase4-tier2-manifest.test.ts b/tests/phase4-tier2-manifest.test.ts new file mode 100644 index 0000000..c0d5fc3 --- /dev/null +++ b/tests/phase4-tier2-manifest.test.ts @@ -0,0 +1,448 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { CrossStackAuditor } from "../src/compliance/auditor.js"; +import { SbomGenerator } from "../src/compliance/sbom.js"; +import { detectContexts } from "../src/detector/tree-walker.js"; +import { PolyDispatcher } from "../src/dispatcher/executor.js"; +import { PolyDoctor } from "../src/doctor/checker.js"; +import { BaseEngine, engineRegistry } from "../src/engines/index.js"; +import { + mutateCartfile, + mutatePackageSwift, + mutatePodfile, +} from "../src/engines/mutators/apple.js"; +import { mutateMixExs, mutateRebarConfig } from "../src/engines/mutators/elixir.js"; +import { + mutateGradleBuild, + mutateGradleCatalog, + mutateIvyXml, + mutatePomXml, + mutateSbtBuild, +} from "../src/engines/mutators/jvm.js"; +import { fetchLatestVersion, scanOutdatedDependencies } from "../src/outdated/checker.js"; +import { executeBatchUpgrade } from "../src/outdated/upgrader.js"; +import { parsePackageSpec } from "../src/purl/parser.js"; +import { fetchRegistryMetadata } from "../src/security/registry.js"; +import { verifyCompositeLockfile, writeCompositeLockfile } from "../src/workspace/lockfile.js"; + +test("Phase 4 PURL - Parses Maven, Gradle, sbt, Hex, Rebar3, Swift, CocoaPods, Carthage specs", () => { + const mvn = parsePackageSpec("maven:com.google.guava:guava@33.2.1-jre"); + assert.equal(mvn.ecosystem, "maven"); + assert.equal(mvn.name, "com.google.guava:guava"); + assert.equal(mvn.version, "33.2.1-jre"); + + const mvnPurl = parsePackageSpec("pkg:maven/com.google.guava/guava@33.2.1-jre"); + assert.equal(mvnPurl.ecosystem, "maven"); + assert.equal(mvnPurl.name, "com.google.guava/guava"); + assert.equal(mvnPurl.version, "33.2.1-jre"); + + const gradle = parsePackageSpec("gradle:io.ktor:ktor-server-core@3.0.0"); + assert.equal(gradle.ecosystem, "gradle"); + assert.equal(gradle.name, "io.ktor:ktor-server-core"); + + const sbt = parsePackageSpec("sbt:org.typelevel:cats-core@2.12.0"); + assert.equal(sbt.ecosystem, "sbt"); + + const hex = parsePackageSpec("pkg:hex/phoenix@1.7.14"); + assert.equal(hex.ecosystem, "hex"); + assert.equal(hex.name, "phoenix"); + assert.equal(hex.version, "1.7.14"); + + const rebar = parsePackageSpec("rebar3:cowboy@2.12.0"); + assert.equal(rebar.ecosystem, "rebar3"); + assert.equal(rebar.name, "cowboy"); + + const spm = parsePackageSpec("swift:apple/swift-nio@2.70.0"); + assert.equal(spm.ecosystem, "swift"); + assert.equal(spm.name, "apple/swift-nio"); + assert.equal(spm.version, "2.70.0"); + + const pod = parsePackageSpec("cocoapods:Alamofire@5.9.1"); + assert.equal(pod.ecosystem, "cocoapods"); + assert.equal(pod.name, "Alamofire"); + + const carthage = parsePackageSpec("carthage:Alamofire/Alamofire@5.9.1"); + assert.equal(carthage.ecosystem, "carthage"); +}); + +test("Phase 4 Mutators - Safe, idempotent JVM AST/manifest edits (pom.xml, ivy.xml, libs.versions.toml, build.gradle(.kts), build.sbt)", () => { + const origPom = [ + '', + "", + " ", + " ", + " org.slf4j", + " slf4j-api", + " 2.0.12", + " ", + " ", + "", + "", + ].join("\n"); + + const guava = parsePackageSpec("maven:com.google.guava:guava@33.1.0-jre"); + const pomAdded = mutatePomXml(origPom, "add", guava); + assert.ok(pomAdded.includes("com.google.guava")); + assert.ok(pomAdded.includes("33.1.0-jre")); + assert.ok(pomAdded.includes(" ")); + // Idempotent on repeat add + assert.equal(mutatePomXml(pomAdded, "add", guava), pomAdded); + // Upsert updates version cleanly + const guavaUp = parsePackageSpec("maven:com.google.guava:guava@33.2.1-jre"); + const pomUpdated = mutatePomXml(pomAdded, "add", guavaUp); + assert.ok(pomUpdated.includes("33.2.1-jre")); + assert.ok(!pomUpdated.includes("33.1.0-jre")); + // Clean removal restores original pom.xml + assert.equal(mutatePomXml(pomUpdated, "remove", guavaUp), origPom); + + // Ivy XML + const origIvy = "\n \n \n\n"; + const ivyAdded = mutateIvyXml(origIvy, "add", guava); + assert.ok(ivyAdded.includes('org="com.google.guava" name="guava" rev="33.1.0-jre"')); + assert.equal(mutateIvyXml(ivyAdded, "add", guava), ivyAdded); + assert.equal(mutateIvyXml(ivyAdded, "remove", guava), origIvy); + + // Gradle Version Catalog (libs.versions.toml) + const origCatalog = '[versions]\nkotlin = "2.0.20"\n\n[libraries]\n'; + const catalogAdded = mutateGradleCatalog(origCatalog, "add", guava); + assert.ok(catalogAdded.includes('guava = "33.1.0-jre"')); + assert.ok( + catalogAdded.includes( + 'guava = { group = "com.google.guava", name = "guava", version.ref = "guava" }', + ), + ); + assert.equal(mutateGradleCatalog(catalogAdded, "add", guava), catalogAdded); + assert.equal(mutateGradleCatalog(catalogAdded, "remove", guava), origCatalog); + + // build.gradle.kts + const origKts = 'dependencies {\n implementation("org.slf4j:slf4j-api:2.0.12")\n}\n'; + const ktsAdded = mutateGradleBuild(origKts, "add", guava, true); + assert.ok(ktsAdded.includes(' implementation("com.google.guava:guava:33.1.0-jre")')); + assert.equal(mutateGradleBuild(ktsAdded, "add", guava, true), ktsAdded); + assert.equal(mutateGradleBuild(ktsAdded, "remove", guava, true), origKts); + + // build.sbt + const origSbt = 'name := "demo"\n'; + const cats = parsePackageSpec("sbt:org.typelevel:cats-core@2.12.0"); + const sbtAdded = mutateSbtBuild(origSbt, "add", cats); + assert.ok(sbtAdded.includes('libraryDependencies += "org.typelevel" %% "cats-core" % "2.12.0"')); + assert.equal(mutateSbtBuild(sbtAdded, "add", cats), sbtAdded); + assert.equal(mutateSbtBuild(sbtAdded, "remove", cats), origSbt); +}); + +test("Phase 4 Mutators - Safe, idempotent Elixir/Erlang & Apple/Swift manifest edits", () => { + const origMix = [ + "defmodule Demo.MixProject do", + " use Mix.Project", + "", + " defp deps do", + " [", + ' {:jason, "~> 1.4"}', + " ]", + " end", + "end", + "", + ].join("\n"); + const phoenix = parsePackageSpec("hex:phoenix@1.7.14"); + const mixAdded = mutateMixExs(origMix, "add", phoenix); + assert.ok(mixAdded.includes('{:jason, "~> 1.4"},')); + assert.ok(mixAdded.includes('{:phoenix, "~> 1.7.14"}')); + assert.equal(mutateMixExs(mixAdded, "add", phoenix), mixAdded); + const mixRemoved = mutateMixExs(mixAdded, "remove", phoenix); + assert.ok(!mixRemoved.includes(":phoenix")); + assert.ok(mixRemoved.includes(":jason")); + + // Rebar3 + const origRebar = '{deps, [\n {jsx, "3.1.0"}\n]}.\n'; + const cowboy = parsePackageSpec("rebar3:cowboy@2.12.0"); + const rebarAdded = mutateRebarConfig(origRebar, "add", cowboy); + assert.ok(rebarAdded.includes('{cowboy, "2.12.0"}')); + assert.equal(mutateRebarConfig(rebarAdded, "add", cowboy), rebarAdded); + assert.ok(!mutateRebarConfig(rebarAdded, "remove", cowboy).includes("cowboy")); + + // Package.swift + const origSwift = [ + "// swift-tools-version: 5.9", + "import PackageDescription", + "", + "let package = Package(", + ' name: "App",', + " dependencies: [", + " ],", + " targets: [", + " .executableTarget(", + ' name: "App",', + " dependencies: [", + " ]", + " )", + " ]", + ")", + "", + ].join("\n"); + const nio = parsePackageSpec("swift:apple/swift-nio@2.70.0"); + const swiftAdded = mutatePackageSwift(origSwift, "add", nio); + assert.ok( + swiftAdded.includes('.package(url: "https://github.com/apple/swift-nio.git", from: "2.70.0"),'), + ); + assert.ok(swiftAdded.includes('.product(name: "swift-nio", package: "swift-nio"),')); + assert.equal(mutatePackageSwift(swiftAdded, "add", nio), swiftAdded); + assert.equal(mutatePackageSwift(swiftAdded, "remove", nio), origSwift); + + // Podfile & Cartfile + const origPodfile = "platform :ios, '15.0'\ntarget 'MyApp' do\nend\n"; + const pod = parsePackageSpec("cocoapods:Alamofire@5.9.1"); + const podAdded = mutatePodfile(origPodfile, "add", pod); + assert.ok(podAdded.includes(" pod 'Alamofire', '~> 5.9.1'")); + assert.equal(mutatePodfile(podAdded, "add", pod), podAdded); + assert.equal(mutatePodfile(podAdded, "remove", pod), origPodfile); + + const origCart = 'github "ReactiveX/RxSwift" ~> 6.7.0\n'; + const cartPkg = parsePackageSpec("carthage:Alamofire/Alamofire@5.9.1"); + const cartAdded = mutateCartfile(origCart, "add", cartPkg); + assert.ok(cartAdded.includes('github "Alamofire/Alamofire" ~> 5.9.1')); + assert.equal(mutateCartfile(cartAdded, "add", cartPkg), cartAdded); + assert.equal(mutateCartfile(cartAdded, "remove", cartPkg), origCart); +}); + +test("Phase 4 Dispatcher - Mutates manifests before executing add/remove CLIs", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase4-disp-")); + const pomDir = path.join(dir, "mvn"); + const mixDir = path.join(dir, "elixir"); + const swiftDir = path.join(dir, "swift"); + for (const d of [pomDir, mixDir, swiftDir]) fs.mkdirSync(d, { recursive: true }); + + fs.writeFileSync( + path.join(pomDir, "pom.xml"), + "\n \n \n\n", + ); + fs.writeFileSync( + path.join(mixDir, "mix.exs"), + "defmodule App.MixProject do\n defp deps do\n []\n end\nend\n", + ); + fs.writeFileSync( + path.join(swiftDir, "Package.swift"), + 'let package = Package(\n dependencies: [],\n targets: [\n .target(name: "App", dependencies: [])\n ]\n)\n', + ); + + const calls: Array<{ command: string; args: string[]; cwd: string }> = []; + const origExec = BaseEngine.prototype.execute; + const origFetch = globalThis.fetch; + globalThis.fetch = (async () => new Response("{}", { status: 404 })) as typeof fetch; + BaseEngine.prototype.execute = async function (command, args, cwd) { + calls.push({ command, args, cwd }); + return { engine: this.name, command, args, exitCode: 0, stdout: "", stderr: "", durationMs: 1 }; + }; + + try { + const dispatcher = new PolyDispatcher(); + await dispatcher.add("maven:org.slf4j:slf4j-api@2.0.12", { + cwd: pomDir, + silent: true, + allowUntested: true, + }); + assert.ok(fs.readFileSync(path.join(pomDir, "pom.xml"), "utf-8").includes("slf4j-api")); + assert.deepEqual(calls[0]?.args, ["dependency:resolve"]); + + await dispatcher.add("hex:phoenix@1.7.14", { cwd: mixDir, silent: true, allowUntested: true }); + assert.ok(fs.readFileSync(path.join(mixDir, "mix.exs"), "utf-8").includes(":phoenix")); + assert.deepEqual(calls[1]?.args, ["deps.get"]); + + await dispatcher.add("swift:apple/swift-nio@2.70.0", { + cwd: swiftDir, + silent: true, + allowUntested: true, + }); + assert.ok(fs.readFileSync(path.join(swiftDir, "Package.swift"), "utf-8").includes("swift-nio")); + assert.deepEqual(calls[2]?.args, ["package", "resolve"]); + + await dispatcher.remove("hex:phoenix", { cwd: mixDir, silent: true }); + assert.ok(!fs.readFileSync(path.join(mixDir, "mix.exs"), "utf-8").includes(":phoenix")); + assert.deepEqual(calls[3]?.args, ["deps.clean", "phoenix", "--unlock"]); + } finally { + BaseEngine.prototype.execute = origExec; + globalThis.fetch = origFetch; + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("Phase 4 Integration - Registries, outdated/upgrader, poly.lock, OSV (Maven/Hex/SwiftURL), SBOM & Doctor", async () => { + const wsDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase4-ws-")); + const mvnDir = path.join(wsDir, "svc-maven"); + const gradleDir = path.join(wsDir, "svc-gradle"); + const sbtDir = path.join(wsDir, "svc-sbt"); + const hexDir = path.join(wsDir, "svc-elixir"); + const swiftDir = path.join(wsDir, "app-swift"); + const podDir = path.join(wsDir, "app-ios"); + + for (const d of [mvnDir, gradleDir, sbtDir, hexDir, swiftDir, podDir]) { + fs.mkdirSync(d, { recursive: true }); + } + fs.mkdirSync(path.join(gradleDir, "gradle"), { recursive: true }); + + fs.writeFileSync( + path.join(mvnDir, "pom.xml"), + "\n \n \n com.google.guava\n guava\n 32.1.0-jre\n \n \n\n", + ); + fs.writeFileSync(path.join(gradleDir, "build.gradle.kts"), 'plugins { kotlin("jvm") }\n'); + fs.writeFileSync( + path.join(gradleDir, "gradle", "libs.versions.toml"), + '[versions]\nktor = "2.3.0"\n\n[libraries]\nktor-core = { group = "io.ktor", name = "ktor-server-core", version.ref = "ktor" }\n', + ); + fs.writeFileSync( + path.join(sbtDir, "build.sbt"), + 'libraryDependencies += "org.typelevel" %% "cats-core" % "2.10.0"\n', + ); + fs.writeFileSync( + path.join(hexDir, "mix.exs"), + 'defmodule Svc.MixProject do\n defp deps do\n [\n {:phoenix, "~> 1.7.10"}\n ]\n end\nend\n', + ); + fs.writeFileSync(path.join(hexDir, "mix.lock"), '%{"phoenix": {:hex, :phoenix, "1.7.10"}}'); + fs.writeFileSync( + path.join(swiftDir, "Package.swift"), + 'let package = Package(\n dependencies: [\n .package(url: "https://github.com/apple/swift-nio.git", from: "2.60.0")\n ]\n)\n', + ); + fs.writeFileSync(path.join(swiftDir, "Package.resolved"), '{"version":2}'); + fs.writeFileSync( + path.join(podDir, "Podfile"), + "target 'Mobile' do\n pod 'Alamofire', '~> 5.8.0'\nend\n", + ); + + const osvQueries: Array<{ package?: { name?: string; ecosystem?: string }; version?: string }> = + []; + const origFetch = globalThis.fetch; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const u = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + + if (u.includes("search.maven.org/solrsearch/select")) { + return new Response( + JSON.stringify({ + response: { + docs: [ + { + v: u.includes("ktor-server-core") + ? "3.0.0" + : u.includes("cats-core") + ? "2.12.0" + : "33.2.1", + timestamp: 1730000000000, + }, + ], + }, + }), + { status: 200 }, + ); + } + if (u.includes("hex.pm/api/packages/phoenix")) { + return new Response( + JSON.stringify({ + latest_stable_version: "1.7.14", + meta: { licenses: ["MIT"] }, + releases: [{ version: "1.7.14", inserted_at: "2025-01-01T00:00:00Z" }], + }), + { status: 200 }, + ); + } + if (u.includes("trunk.cocoapods.org/api/v1/pods/Alamofire")) { + return new Response( + JSON.stringify({ + versions: [{ name: "5.9.1", created_at: "2025-02-01T00:00:00Z" }], + }), + { status: 200 }, + ); + } + if (u.includes("api.github.com/repos/apple/swift-nio/tags")) { + return new Response(JSON.stringify([{ name: "2.70.0" }]), { status: 200 }); + } + if (u.includes("api.osv.dev/v1/querybatch")) { + const body = JSON.parse(String(init?.body ?? "{}")) as { + queries?: Array<{ package?: { name?: string; ecosystem?: string }; version?: string }>; + }; + const queries = body.queries ?? []; + osvQueries.push(...queries); + const results = queries.map((q) => + q.package?.ecosystem === "Maven" && q.package?.name === "com.google.guava:guava" + ? { vulns: [{ id: "GHSA-maven-guava-test", summary: "Mock Maven advisory" }] } + : {}, + ); + return new Response(JSON.stringify({ results }), { status: 200 }); + } + return new Response("{}", { status: 200 }); + }) as typeof fetch; + + try { + // 1. Detector + Dispatcher CLI resolution + assert.equal(detectContexts(mvnDir)[0]?.manifestFile, "pom.xml"); + assert.equal(detectContexts(gradleDir)[0]?.ecosystem, "gradle"); + assert.equal(detectContexts(sbtDir)[0]?.manifestFile, "build.sbt"); + assert.equal(detectContexts(hexDir)[0]?.manifestFile, "mix.exs"); + assert.equal(detectContexts(swiftDir)[0]?.manifestFile, "Package.swift"); + assert.equal(detectContexts(podDir)[0]?.manifestFile, "Podfile"); + + assert.equal(engineRegistry.createEngine("maven").getEffectiveCli(), "mvn"); + assert.equal(engineRegistry.createEngine("gradle").getEffectiveCli(), "gradle"); + assert.equal(engineRegistry.createEngine("hex").getEffectiveCli(), "mix"); + assert.equal(engineRegistry.createEngine("swift").getEffectiveCli(), "swift"); + + // 2. poly.lock + CycloneDX SBOM (canonical PURLs including pkg:maven/g/a) + const lock = writeCompositeLockfile(wsDir); + assert.equal(lock.members.length, 6); + assert.equal(verifyCompositeLockfile(wsDir).isDrifted, false); + + const sbom = JSON.parse(new SbomGenerator().generate(wsDir, { format: "cyclonedx" })) as { + components: Array<{ purl: string }>; + }; + const purls = sbom.components.map((c) => c.purl); + assert.ok(purls.some((p) => p.startsWith("pkg:maven/com.google.guava/guava@32.1.0-jre"))); + assert.ok(purls.some((p) => p.startsWith("pkg:maven/io.ktor/ktor-server-core@2.3.0"))); + assert.ok(purls.some((p) => p.startsWith("pkg:hex/phoenix@1.7.10"))); + assert.ok(purls.some((p) => p.startsWith("pkg:swift/github.com/apple/swift-nio@2.60.0"))); + + // 3. Registry Metadata + Outdated Scan + Batch Manifest Upgrade + assert.equal(await fetchLatestVersion("com.google.guava:guava", "maven"), "33.2.1"); + assert.equal(await fetchLatestVersion("phoenix", "hex"), "1.7.14"); + assert.equal(await fetchLatestVersion("Alamofire", "cocoapods"), "5.9.1"); + assert.equal(await fetchLatestVersion("github.com/apple/swift-nio", "swift"), "2.70.0"); + + const hexMeta = await fetchRegistryMetadata("hex", "phoenix"); + assert.equal(hexMeta?.versions["1.7.14"]?.license, "MIT"); + const mavenMeta = await fetchRegistryMetadata("maven", "com.google.guava:guava"); + assert.equal(mavenMeta?.latestVersion, "33.2.1"); + + const outdated = await scanOutdatedDependencies(wsDir); + assert.ok(outdated.outdatedCount >= 4); + + const upgraded = await executeBatchUpgrade(wsDir, { + packages: ["com.google.guava:guava", "phoenix", "github.com/apple/swift-nio", "Alamofire"], + }); + assert.equal(upgraded.totalUpgraded, 4); + assert.equal(upgraded.lockfileUpdated, true); + assert.ok(fs.readFileSync(path.join(mvnDir, "pom.xml"), "utf-8").includes("33.2.1")); + assert.ok(fs.readFileSync(path.join(hexDir, "mix.exs"), "utf-8").includes("1.7.14")); + assert.ok(fs.readFileSync(path.join(swiftDir, "Package.swift"), "utf-8").includes("2.70.0")); + assert.ok(fs.readFileSync(path.join(podDir, "Podfile"), "utf-8").includes("5.9.1")); + + // 4. OSV audit maps Maven, Hex, SwiftURL while skipping CocoaPods gracefully + const audit = await new CrossStackAuditor().audit(wsDir); + assert.ok(osvQueries.some((q) => q.package?.ecosystem === "Maven")); + assert.ok( + osvQueries.some((q) => q.package?.ecosystem === "Hex" && q.package?.name === "phoenix"), + ); + assert.ok( + osvQueries.some( + (q) => + q.package?.ecosystem === "SwiftURL" && q.package?.name === "github.com/apple/swift-nio", + ), + ); + assert.ok(!osvQueries.some((q) => q.package?.ecosystem === "cocoapods")); + assert.ok(audit.findings.some((f) => f.id === "GHSA-maven-guava-test")); + + const doctor = await new PolyDoctor().diagnose(wsDir); + assert.equal(doctor.checks.find((c) => c.id === "workspace-lock-drift")?.status, "OK"); + } finally { + globalThis.fetch = origFetch; + fs.rmSync(wsDir, { recursive: true, force: true }); + } +});