diff --git a/src/cli.ts b/src/cli.ts index dba0dd9..a7d6bb0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -29,6 +29,7 @@ import { detectContexts, resolvePrimaryContext } from "./detector/index.js"; import { PolyDispatcher } from "./dispatcher/index.js"; import { DockerGenerator } from "./docker/index.js"; import { PolyDoctor } from "./doctor/index.js"; +import { engineRegistry } from "./engines/registry.js"; import { PolyMcpServer, generateMcpConfig, @@ -89,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, pypi, cargo, go) + which Show active CLI binary for an ecosystem (npm, jsr, pypi, conda, cargo, go) OPTIONS: -D, --dev Install as a development dependency @@ -1064,13 +1065,18 @@ async function main(): Promise { case "which": { const ecosystem = positionalArgs[0]?.toLowerCase() as Ecosystem; - if (!ecosystem || !["npm", "pypi", "cargo", "go"].includes(ecosystem)) { - logError("Please specify a valid ecosystem: 'npm', 'pypi', 'cargo', or 'go'"); + const resolved = ecosystem ? engineRegistry.resolveEcosystem(ecosystem) : undefined; + if (!resolved) { + const supported = engineRegistry + .listEcosystems() + .map((e) => `'${e}'`) + .join(", "); + logError(`Please specify a valid ecosystem: ${supported}`); process.exit(1); } const dispatcher = new PolyDispatcher(); - const info = dispatcher.which(ecosystem, cwd); + const info = dispatcher.which(resolved, cwd); if (isJson) { console.log(JSON.stringify({ ecosystem, ...info }, null, 2)); } else { diff --git a/src/completion/generator.ts b/src/completion/generator.ts index 6b66220..1762fe7 100644 --- a/src/completion/generator.ts +++ b/src/completion/generator.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import { engineRegistry } from "../engines/registry.js"; import { loadWorkspaceConfig, resolveWorkspaceMembers } from "../workspace/config.js"; import type { CommandDefinition, SupportedShell } from "./types.js"; @@ -185,7 +186,7 @@ export function resolveDynamicCompletions(type: string, cwd: string = process.cw case "which": case "ecosystems": - return ["npm", "pypi", "cargo", "go"]; + return engineRegistry.listEcosystems(); case "shells": return ["bash", "zsh", "fish", "powershell"]; @@ -303,7 +304,7 @@ ${zshEntries} _values 'shell' bash zsh fish powershell ;; which) - _values 'ecosystem' npm pypi cargo go + _values 'ecosystem' ${engineRegistry.listEcosystems().join(" ")} ;; run) local -a tasks @@ -386,7 +387,10 @@ ${psEntries} ForEach-Object { [System.Management.Automation.CompletionResult]::new(\$_, \$_, "ParameterValue", "\$_ shell completion") } } "which" { - @("npm", "pypi", "cargo", "go") | + @(${engineRegistry + .listEcosystems() + .map((e) => `"${e}"`) + .join(", ")}) | Where-Object { \$_ -like "\$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new(\$_, \$_, "ParameterValue", "Ecosystem package manager") } } diff --git a/src/compliance/auditor.ts b/src/compliance/auditor.ts index 50e5542..4a02aa0 100644 --- a/src/compliance/auditor.ts +++ b/src/compliance/auditor.ts @@ -62,8 +62,8 @@ export class CrossStackAuditor { if (lock) { for (const member of lock.members) { for (const depStr of member.directDependencies) { - // format: "npm:axios@^1.7.0" or "pypi:fastapi@>=0.110.0" - const match = depStr.match(/^([a-z]+):(.*)$/); + // format: "npm:axios@^1.7.0", "jsr:@std/path@^1.0.0", "conda:numpy@1.26.4" + const match = depStr.match(/^([a-z0-9_-]+):(.*)$/); if (match) { const ecosystem = match[1] as Ecosystem; const rest = match[2]; diff --git a/src/compliance/licenses.ts b/src/compliance/licenses.ts index 45070ed..b27a83d 100644 --- a/src/compliance/licenses.ts +++ b/src/compliance/licenses.ts @@ -42,7 +42,7 @@ export class LicenseAuditor { if (lock) { for (const member of lock.members) { for (const depStr of member.directDependencies) { - const match = depStr.match(/^([a-z]+):(.*)$/); + const match = depStr.match(/^([a-z0-9_-]+):(.*)$/); if (match) { const ecosystem = match[1] as Ecosystem; const rest = match[2]; diff --git a/src/compliance/osv.ts b/src/compliance/osv.ts index b385966..e950307 100644 --- a/src/compliance/osv.ts +++ b/src/compliance/osv.ts @@ -1,3 +1,4 @@ +import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem } from "../types.js"; import type { AuditFinding, VulnerabilitySeverity } from "./types.js"; @@ -57,14 +58,20 @@ export class OsvClient { async queryPackages( packages: Array<{ name: string; ecosystem: Ecosystem; version: string; memberPath: string }>, ): Promise { - if (packages.length === 0) { + const queryable = packages + .map((pkg) => ({ pkg, osvEcosystem: this.mapEcosystemToOsv(pkg.ecosystem) })) + .filter((entry): entry is { pkg: (typeof packages)[number]; osvEcosystem: string } => + Boolean(entry.osvEcosystem), + ); + + if (queryable.length === 0) { return []; } - const queries: OsvQueryItem[] = packages.map((pkg) => ({ + const queries: OsvQueryItem[] = queryable.map(({ pkg, osvEcosystem }) => ({ package: { name: pkg.name, - ecosystem: this.mapEcosystemToOsv(pkg.ecosystem), + ecosystem: osvEcosystem, }, version: pkg.version.replace(/^[~^>=<]/, "").trim(), })); @@ -89,7 +96,7 @@ export class OsvClient { data.results?.forEach((result, idx) => { if (!result.vulns || result.vulns.length === 0) return; - const targetPkg = packages[idx]; + const targetPkg = queryable[idx].pkg; for (const vuln of result.vulns) { const severity = this.normalizeSeverity(vuln); @@ -133,17 +140,8 @@ export class OsvClient { } } - private mapEcosystemToOsv(ecosystem: Ecosystem): string { - switch (ecosystem) { - case "npm": - return "npm"; - case "pypi": - return "PyPI"; - case "cargo": - return "crates.io"; - case "go": - return "Go"; - } + private mapEcosystemToOsv(ecosystem: Ecosystem): string | undefined { + return engineRegistry.getOsvEcosystem(ecosystem); } private normalizeSeverity(vuln: { diff --git a/src/compliance/sbom.ts b/src/compliance/sbom.ts index 4c33145..c172ae4 100644 --- a/src/compliance/sbom.ts +++ b/src/compliance/sbom.ts @@ -1,5 +1,6 @@ import crypto from "node:crypto"; import fs from "node:fs"; +import { engineRegistry } from "../engines/registry.js"; import { readCompositeLockfile } from "../workspace/lockfile.js"; import { LicenseAuditor } from "./licenses.js"; import type { SbomOptions } from "./types.js"; @@ -39,7 +40,7 @@ export class SbomGenerator { const serialUuid = crypto.randomUUID(); const components = packages.map((pkg) => { - const purlEcosystem = pkg.ecosystem === "go" ? "golang" : pkg.ecosystem; + const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem); return { type: "library", name: pkg.packageName, @@ -88,7 +89,7 @@ export class SbomGenerator { ): string { const spdxPackages = packages.map((pkg, idx) => { const safeId = pkg.packageName.replace(/[^a-zA-Z0-9]/g, "-"); - const purlEcosystem = pkg.ecosystem === "go" ? "golang" : pkg.ecosystem; + const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem); return { name: pkg.packageName, SPDXID: `SPDXRef-Package-${safeId}-${idx}`, diff --git a/src/detector/index.ts b/src/detector/index.ts index 944122a..59737e1 100644 --- a/src/detector/index.ts +++ b/src/detector/index.ts @@ -1 +1 @@ -export { detectContexts, resolvePrimaryContext } from "./tree-walker.js"; +export { detectContexts, matchesManifestGlob, resolvePrimaryContext } from "./tree-walker.js"; diff --git a/src/detector/tree-walker.ts b/src/detector/tree-walker.ts index b8187dc..ac35936 100644 --- a/src/detector/tree-walker.ts +++ b/src/detector/tree-walker.ts @@ -1,39 +1,55 @@ import fs from "node:fs"; import path from "node:path"; +import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem, ManifestContext } from "../types.js"; -interface EcosystemRule { - ecosystem: Ecosystem; - manifests: string[]; - lockfiles: string[]; +/** + * Matches a single filename against an exact pattern or simple wildcard glob (e.g. *.csproj, *.rockspec, *.cabal). + */ +export function matchesManifestGlob(filename: string, pattern: string): boolean { + if (!pattern.includes("*") && !pattern.includes("?")) { + return filename === pattern; + } + const escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + return new RegExp(`^${escaped}$`, "i").test(filename); } -const ECOSYSTEM_RULES: EcosystemRule[] = [ - { - ecosystem: "npm", - manifests: ["package.json"], - lockfiles: ["pnpm-lock.yaml", "bun.lockb", "bun.lock", "yarn.lock", "package-lock.json"], - }, - { - ecosystem: "pypi", - manifests: ["pyproject.toml", "requirements.txt", "Pipfile", "setup.py"], - lockfiles: ["uv.lock", "poetry.lock", "Pipfile.lock"], - }, - { - ecosystem: "cargo", - manifests: ["Cargo.toml"], - lockfiles: ["Cargo.lock"], - }, - { - ecosystem: "go", - manifests: ["go.mod"], - lockfiles: ["go.sum"], - }, -]; +function findMatchingManifest( + dir: string, + patterns: readonly string[], + cachedEntries?: string[], +): { matched?: string; entries?: string[] } { + let entries = cachedEntries; + + for (const pattern of patterns) { + if (!pattern.includes("*") && !pattern.includes("?")) { + if (fs.existsSync(path.join(dir, pattern))) { + return { matched: pattern, entries }; + } + } else { + if (!entries) { + try { + entries = fs.readdirSync(dir).sort(); + } catch { + entries = []; + } + } + const hit = entries.find((entry) => matchesManifestGlob(entry, pattern)); + if (hit) { + return { matched: hit, entries }; + } + } + } + + return { matched: undefined, entries }; +} /** * Traverses upwards from the start directory up to the git root or system root, - * collecting all project manifests and computing proximity scores. + * collecting all project manifests via EngineRegistry and computing proximity scores. */ export function detectContexts(startDir: string): ManifestContext[] { let current = path.resolve(startDir); @@ -42,34 +58,38 @@ export function detectContexts(startDir: string): ManifestContext[] { const visitedEcosystems = new Set(); while (true) { - for (const rule of ECOSYSTEM_RULES) { - if (visitedEcosystems.has(rule.ecosystem)) { + let dirEntriesCache: string[] | undefined; + + for (const adapter of engineRegistry.getAdapters()) { + if (visitedEcosystems.has(adapter.ecosystem)) { continue; } - for (const manifest of rule.manifests) { - const manifestPath = path.join(current, manifest); - if (fs.existsSync(manifestPath)) { - let foundLockfile: string | undefined; - for (const lockfile of rule.lockfiles) { - const lockPath = path.join(current, lockfile); - if (fs.existsSync(lockPath)) { - foundLockfile = lockfile; - break; - } + const { matched: matchedManifest, entries } = findMatchingManifest( + current, + adapter.manifests, + dirEntriesCache, + ); + dirEntriesCache = entries; + + if (matchedManifest) { + let foundLockfile: string | undefined; + for (const lockfile of adapter.lockfiles) { + if (fs.existsSync(path.join(current, lockfile))) { + foundLockfile = lockfile; + break; } + } - contexts.push({ - directory: current, - ecosystem: rule.ecosystem, - manifestFile: manifest, - lockfile: foundLockfile, - distance, - }); + contexts.push({ + directory: current, + ecosystem: adapter.ecosystem, + manifestFile: matchedManifest, + lockfile: foundLockfile, + distance, + }); - visitedEcosystems.add(rule.ecosystem); - break; - } + visitedEcosystems.add(adapter.ecosystem); } } diff --git a/src/dispatcher/executor.ts b/src/dispatcher/executor.ts index bd4d776..466aa26 100644 --- a/src/dispatcher/executor.ts +++ b/src/dispatcher/executor.ts @@ -1,11 +1,5 @@ import { detectContexts, resolvePrimaryContext } from "../detector/tree-walker.js"; -import { - type BaseEngine, - GoEngine, - NodeEngine, - PythonEngine, - RustEngine, -} from "../engines/index.js"; +import { type BaseEngine, engineRegistry } from "../engines/index.js"; import { parsePackageSpec } from "../purl/parser.js"; import { RegistryRouter } from "../registry/index.js"; import { evaluateSandboxGate, injectSandboxFlags } from "../sandbox/index.js"; @@ -299,13 +293,7 @@ export class PolyDispatcher { */ which(ecosystem: Ecosystem, cwd?: string): { engine: string; effectiveCli: string } { const engine = this.getEngineForEcosystem(ecosystem, cwd ?? process.cwd()); - let effectiveCli = engine.name; - if (engine instanceof NodeEngine) { - effectiveCli = engine.getEffectiveCli(); - } else if (engine instanceof PythonEngine) { - effectiveCli = engine.getEffectiveCli(); - } - return { engine: engine.name, effectiveCli }; + return { engine: engine.name, effectiveCli: engine.getEffectiveCli() }; } private async resolveEcosystemForPackage( @@ -328,8 +316,8 @@ export class PolyDispatcher { throw new Error( `Could not determine ecosystem for '${packageName}'.\n` + - `No manifest (package.json, pyproject.toml, Cargo.toml, go.mod) was found in '${cwd}' or its parents.\n` + - `Remediation: Pass an explicit ecosystem prefix, e.g. 'npm:${packageName}' or 'pypi:${packageName}'.`, + `No manifest (package.json, deno.json, pyproject.toml, environment.yml, Cargo.toml, go.mod) was found in '${cwd}' or its parents.\n` + + `Remediation: Pass an explicit ecosystem prefix, e.g. 'npm:${packageName}', 'jsr:@scope/pkg', 'pypi:${packageName}', or 'conda:${packageName}'.`, ); } @@ -337,15 +325,11 @@ export class PolyDispatcher { const contexts = detectContexts(cwd); const ctx = contexts.find((c) => c.ecosystem === ecosystem); - switch (ecosystem) { - case "npm": - return new NodeEngine(ctx?.lockfile); - case "pypi": - return new PythonEngine(ctx?.lockfile); - case "cargo": - return new RustEngine(); - case "go": - return new GoEngine(); - } + return engineRegistry.createEngine(ecosystem, { + cwd, + ecosystem, + manifest: ctx?.manifestFile, + lockfile: ctx?.lockfile, + }); } } diff --git a/src/doctor/checker.ts b/src/doctor/checker.ts index b90a5e6..4002c17 100644 --- a/src/doctor/checker.ts +++ b/src/doctor/checker.ts @@ -75,27 +75,31 @@ export class PolyDoctor { }); } - // Node Package Managers - const managers: Array<{ name: string; cmd: string }> = [ - { name: "pnpm", cmd: "pnpm" }, - { name: "bun", cmd: "bun" }, - { name: "yarn", cmd: "yarn" }, - { name: "npm", cmd: "npm" }, + // Node / Deno JS & TS Package Managers + const managers: Array<{ name: string; cmd: string; args: string[] }> = [ + { name: "pnpm", cmd: "pnpm", args: ["-v"] }, + { name: "bun", cmd: "bun", args: ["-v"] }, + { name: "yarn", cmd: "yarn", args: ["-v"] }, + { name: "npm", cmd: "npm", args: ["-v"] }, + { name: "deno", cmd: "deno", args: ["--version"] }, ]; const availableManagers: string[] = []; for (const m of managers) { - const res = this.runCommandSafe(m.cmd, ["-v"]); + const res = this.runCommandSafe(m.cmd, m.args); if (res.available) { - availableManagers.push(`${m.name} (${res.output.trim()})`); + const firstLine = res.output.trim().split(/\r?\n/)[0].trim(); + availableManagers.push(`${m.name} (${firstLine})`); } } if (availableManagers.length > 0) { - const hasFast = availableManagers.some((m) => m.startsWith("pnpm") || m.startsWith("bun")); + const hasFast = availableManagers.some( + (m) => m.startsWith("pnpm") || m.startsWith("bun") || m.startsWith("deno"), + ); checks.push({ id: "toolchain-node-managers", - name: "Node Package Managers", + name: "JS/TS Package Managers (Node / Deno)", category: "Toolchain", status: "OK", message: `Detected: ${availableManagers.join(", ")}${hasFast ? " (High-speed runner ready)" : ""}`, @@ -103,10 +107,10 @@ export class PolyDoctor { } else { checks.push({ id: "toolchain-node-managers", - name: "Node Package Managers", + name: "JS/TS Package Managers (Node / Deno)", category: "Toolchain", status: "FAIL", - message: "No Node package manager (pnpm, bun, yarn, npm) found in PATH.", + message: "No JS/TS package manager (pnpm, bun, yarn, npm, deno) found in PATH.", remediation: "Install npm or pnpm globally: npm install -g pnpm", }); } @@ -142,24 +146,41 @@ export class PolyDoctor { }); } - // Check uv - const uvRes = this.runCommandSafe("uv", ["--version"]); - if (uvRes.available) { + // Check Python ecosystem package managers (uv, poetry, pipenv, conda, mamba) + const pyManagers: Array<{ name: string; cmd: string; args: string[] }> = [ + { name: "uv", cmd: "uv", args: ["--version"] }, + { name: "poetry", cmd: "poetry", args: ["--version"] }, + { name: "pipenv", cmd: "pipenv", args: ["--version"] }, + { name: "mamba", cmd: "mamba", args: ["--version"] }, + { name: "conda", cmd: "conda", args: ["--version"] }, + ]; + const detectedPyManagers: string[] = []; + for (const m of pyManagers) { + const res = this.runCommandSafe(m.cmd, m.args); + if (res.available) { + detectedPyManagers.push(`${m.name} (${res.output.trim().split(/\r?\n/)[0].trim()})`); + } + } + + if (detectedPyManagers.some((d) => d.startsWith("uv"))) { checks.push({ id: "toolchain-python-uv", - name: "Astral uv Package Manager", + name: "Python Package Managers", category: "Toolchain", status: "OK", - version: uvRes.output.trim(), - message: `uv active (${uvRes.output.trim()}) — ultra-fast sub-second resolver enabled`, + version: detectedPyManagers[0], + message: `Detected: ${detectedPyManagers.join(", ")} — ultra-fast resolver ready`, }); } else if (pyRes.available) { checks.push({ id: "toolchain-python-uv", - name: "Astral uv Package Manager", + name: "Python Package Managers", category: "Toolchain", status: "WARN", - message: "uv is not installed. Falling back to pip/poetry (10x-50x slower).", + message: + detectedPyManagers.length > 0 + ? `Detected ${detectedPyManagers.join(", ")}. uv is not installed (10x-50x faster fallback available).` + : "uv is not installed. Falling back to pip (10x-50x slower).", remediation: "Install uv for lightning-fast Python installs: curl -LsSf https://astral.sh/uv/install.sh | sh", }); @@ -249,6 +270,7 @@ export class PolyDoctor { ): Promise { const defaultEndpoints = [ { name: "npm Registry", url: "https://registry.npmjs.org" }, + { name: "JSR Registry", url: "https://jsr.io" }, { name: "PyPI Simple API", url: "https://pypi.org/simple" }, { name: "crates.io", url: "https://crates.io" }, ]; diff --git a/src/engines/base.ts b/src/engines/base.ts index f0c34a0..e21af79 100644 --- a/src/engines/base.ts +++ b/src/engines/base.ts @@ -5,6 +5,13 @@ export abstract class BaseEngine { abstract readonly name: string; abstract readonly ecosystem: string; + /** + * Returns the effective CLI executable resolved for this engine instance. + */ + getEffectiveCli(): string { + return this.name; + } + /** * Checks if an executable command is available in the current PATH. */ diff --git a/src/engines/declarative.ts b/src/engines/declarative.ts new file mode 100644 index 0000000..da9f8c6 --- /dev/null +++ b/src/engines/declarative.ts @@ -0,0 +1,144 @@ +import type { RegistryEndpoint } from "../registry/types.js"; +import type { Ecosystem, EngineContext, PackageSpec } from "../types.js"; +import { BaseEngine } from "./base.js"; + +export interface DeclarativeCommandSpec { + /** Primary CLI binary or resolver for dynamic manager selection (e.g. ["mamba", "conda"]). */ + command: string | readonly string[] | ((ctx?: EngineContext) => string); + /** Formats add command arguments for a parsed PackageSpec. */ + add: (pkg: PackageSpec, ctx?: EngineContext) => string[]; + /** Formats remove command arguments for a parsed PackageSpec. */ + remove: (pkg: PackageSpec, ctx?: EngineContext) => string[]; + /** Formats workspace/project install/sync command arguments. */ + install: (ctx?: EngineContext) => string[]; + /** Formats dependency update command arguments. */ + update: (pkg?: PackageSpec, ctx?: EngineContext) => string[]; +} + +export interface EngineAdapter { + readonly id: string; + readonly ecosystem: Ecosystem; + readonly aliases?: readonly string[]; + readonly purlTypes?: readonly string[]; + /** Exact filenames or wildcard globs (e.g. "*.csproj", "*.rockspec", "*.cabal"). */ + readonly manifests: readonly string[]; + readonly lockfiles: readonly string[]; + readonly osvEcosystem?: string; + readonly sbomPurlType?: string; + readonly defaultCli: string; + readonly supportedClis?: readonly string[]; + createEngine(ctx?: EngineContext): BaseEngine; + resolveScriptCommand?: (script: string, ctx?: EngineContext) => [string, string[]]; + injectRegistryEnv?: (endpoint: RegistryEndpoint, env: NodeJS.ProcessEnv) => void; + injectRegistryFlags?: (endpoint: RegistryEndpoint, args: string[]) => void; + injectSandboxFlags?: (command: string, args: string[]) => string[]; + resolveEphemeralCommand?: ( + spec: PackageSpec, + trailingArgs: string[], + commandExists: (cmd: string) => boolean, + ) => { command: string; args: string[] } | null; +} + +/** + * Declarative CLI engine enabling Tier 1 package managers to be added in ~20 lines of config. + */ +export class DeclarativeEngine extends BaseEngine { + readonly name: string; + readonly ecosystem: Ecosystem; + private readonly spec: DeclarativeCommandSpec; + private readonly ctx?: EngineContext; + private readonly activeCommand: string; + + constructor( + name: string, + ecosystem: Ecosystem, + spec: DeclarativeCommandSpec, + ctx?: EngineContext, + ) { + super(); + this.name = name; + this.ecosystem = ecosystem; + this.spec = spec; + this.ctx = ctx; + this.activeCommand = this.resolveCommand(); + } + + private resolveCommand(): string { + if (this.ctx?.preferredCli) return this.ctx.preferredCli; + if (typeof this.spec.command === "function") return this.spec.command(this.ctx); + if (typeof this.spec.command === "string") return this.spec.command; + for (const candidate of this.spec.command) { + if (this.isCommandAvailable(candidate)) return candidate; + } + return this.spec.command[0]; + } + + override getEffectiveCli(): string { + return this.activeCommand; + } + + resolveAddArgs(pkg: PackageSpec): { command: string; args: string[] } { + return { command: this.activeCommand, args: this.spec.add(pkg, this.ctx) }; + } + + resolveRemoveArgs(pkg: PackageSpec): { command: string; args: string[] } { + return { command: this.activeCommand, args: this.spec.remove(pkg, this.ctx) }; + } + + resolveInstallArgs(): { command: string; args: string[] } { + return { command: this.activeCommand, args: this.spec.install(this.ctx) }; + } + + resolveUpdateArgs(pkg?: PackageSpec): { command: string; args: string[] } { + return { command: this.activeCommand, args: this.spec.update(pkg, this.ctx) }; + } +} + +/** + * Helper factory to define a declarative EngineAdapter for Tier 1 CLI package managers in ~20 lines. + */ +export function defineDeclarativeAdapter(config: { + id: string; + ecosystem: Ecosystem; + aliases?: readonly string[]; + purlTypes?: readonly string[]; + manifests: readonly string[]; + lockfiles: readonly string[]; + osvEcosystem?: string; + sbomPurlType?: string; + commands: DeclarativeCommandSpec; + supportedClis?: readonly string[]; + resolveScriptCommand?: (script: string, ctx?: EngineContext) => [string, string[]]; + injectRegistryEnv?: (endpoint: RegistryEndpoint, env: NodeJS.ProcessEnv) => void; + injectRegistryFlags?: (endpoint: RegistryEndpoint, args: string[]) => void; + injectSandboxFlags?: (command: string, args: string[]) => string[]; + resolveEphemeralCommand?: EngineAdapter["resolveEphemeralCommand"]; +}): EngineAdapter { + const defaultCli = + typeof config.commands.command === "string" + ? config.commands.command + : Array.isArray(config.commands.command) + ? config.commands.command[0] + : config.id; + + return { + id: config.id, + ecosystem: config.ecosystem, + aliases: config.aliases, + purlTypes: config.purlTypes, + manifests: config.manifests, + lockfiles: config.lockfiles, + osvEcosystem: config.osvEcosystem, + sbomPurlType: config.sbomPurlType, + defaultCli, + supportedClis: + config.supportedClis ?? + (Array.isArray(config.commands.command) ? config.commands.command : [defaultCli]), + createEngine: (ctx) => new DeclarativeEngine(config.id, config.ecosystem, config.commands, ctx), + resolveScriptCommand: config.resolveScriptCommand, + injectRegistryEnv: config.injectRegistryEnv, + injectRegistryFlags: config.injectRegistryFlags, + injectSandboxFlags: config.injectSandboxFlags, + resolveEphemeralCommand: config.resolveEphemeralCommand, + }; +} diff --git a/src/engines/index.ts b/src/engines/index.ts index 39d6acc..cf0909b 100644 --- a/src/engines/index.ts +++ b/src/engines/index.ts @@ -1,5 +1,16 @@ export { BaseEngine } from "./base.js"; -export { NodeEngine } from "./node.js"; -export { PythonEngine } from "./python.js"; -export { RustEngine } from "./rust.js"; +export { + DeclarativeEngine, + defineDeclarativeAdapter, + type DeclarativeCommandSpec, + type EngineAdapter, +} from "./declarative.js"; export { GoEngine } from "./go.js"; +export { NodeEngine, type NodeCli } from "./node.js"; +export { PythonEngine, type PythonCli } from "./python.js"; +export { + EngineRegistry, + engineRegistry, + resolveEcosystemLockContext, +} from "./registry.js"; +export { RustEngine } from "./rust.js"; diff --git a/src/engines/node.ts b/src/engines/node.ts index 2ceb708..3aeb415 100644 --- a/src/engines/node.ts +++ b/src/engines/node.ts @@ -1,47 +1,91 @@ -import type { PackageSpec } from "../types.js"; +import type { EngineContext, PackageSpec } from "../types.js"; import { BaseEngine } from "./base.js"; +export type NodeCli = "pnpm" | "bun" | "yarn" | "npm" | "deno"; + +const NODE_CLIS = new Set(["pnpm", "bun", "yarn", "npm", "deno"]); + +function normalizeContext(preferred?: string | EngineContext): EngineContext { + if (!preferred) return {}; + if (typeof preferred === "string") return { lockfile: preferred }; + return preferred; +} + export class NodeEngine extends BaseEngine { readonly name = "node"; - readonly ecosystem = "npm"; - private activeCli: "pnpm" | "bun" | "yarn" | "npm"; + readonly ecosystem: string; + private readonly activeCli: NodeCli; - constructor(preferredLockfile?: string) { + constructor(preferred?: string | EngineContext) { super(); - this.activeCli = this.detectActiveCli(preferredLockfile); + const ctx = normalizeContext(preferred); + this.ecosystem = ctx.ecosystem ?? "npm"; + this.activeCli = this.detectActiveCli(ctx); } - private detectActiveCli(lockfile?: string): "pnpm" | "bun" | "yarn" | "npm" { + private detectActiveCli(ctx: EngineContext): NodeCli { + if (ctx.preferredCli && NODE_CLIS.has(ctx.preferredCli)) { + return ctx.preferredCli as NodeCli; + } + + const { lockfile, manifest, ecosystem } = ctx; + if (lockfile === "deno.lock" || manifest === "deno.json" || manifest === "deno.jsonc") { + return "deno"; + } + if (lockfile === "pnpm-lock.yaml" && this.isCommandAvailable("pnpm")) return "pnpm"; - if ((lockfile === "bun.lockb" || lockfile === "bun.lock") && this.isCommandAvailable("bun")) + if ((lockfile === "bun.lockb" || lockfile === "bun.lock") && this.isCommandAvailable("bun")) { return "bun"; + } if (lockfile === "yarn.lock" && this.isCommandAvailable("yarn")) return "yarn"; if (lockfile === "package-lock.json" && this.isCommandAvailable("npm")) return "npm"; - // Fallback detection priority + if (ecosystem === "jsr") { + if (this.isCommandAvailable("deno") || !manifest) return "deno"; + } + if (this.isCommandAvailable("pnpm")) return "pnpm"; if (this.isCommandAvailable("bun")) return "bun"; if (this.isCommandAvailable("yarn")) return "yarn"; return "npm"; } - getEffectiveCli(): string { + override getEffectiveCli(): string { return this.activeCli; } resolveAddArgs(pkg: PackageSpec): { command: string; args: string[] } { - const pkgTarget = this.formatPackageTarget(pkg); - const args: string[] = []; + const baseTarget = this.formatBaseTarget(pkg); + if (this.activeCli === "deno") { + const scheme = pkg.ecosystem === "jsr" ? "jsr:" : "npm:"; + return { command: "deno", args: ["add", `${scheme}${baseTarget}`] }; + } + + // JSR inside an existing Node.js (package.json) workspace via npx/dlx/bunx jsr add + if (pkg.ecosystem === "jsr") { + switch (this.activeCli) { + case "pnpm": + return { command: "pnpm", args: ["dlx", "jsr", "add", baseTarget] }; + case "bun": + return { command: "bun", args: ["x", "jsr", "add", baseTarget] }; + case "yarn": + return { command: "yarn", args: ["dlx", "jsr", "add", baseTarget] }; + case "npm": + return { command: "npm", args: ["exec", "--yes", "--", "jsr", "add", baseTarget] }; + } + } + + const args: string[] = []; switch (this.activeCli) { case "pnpm": case "bun": case "yarn": - args.push("add", pkgTarget); + args.push("add", baseTarget); if (pkg.isDev) args.push("-D"); break; case "npm": - args.push("install", pkgTarget); + args.push("install", baseTarget); if (pkg.isDev) args.push("--save-dev"); break; } @@ -51,20 +95,17 @@ export class NodeEngine extends BaseEngine { resolveRemoveArgs(pkg: PackageSpec): { command: string; args: string[] } { const pkgName = pkg.namespace ? `${pkg.namespace}/${pkg.name}` : pkg.name; - const args: string[] = []; switch (this.activeCli) { + case "deno": + return { command: "deno", args: ["remove", pkgName] }; case "pnpm": case "bun": case "yarn": - args.push("remove", pkgName); - break; + return { command: this.activeCli, args: ["remove", pkgName] }; case "npm": - args.push("uninstall", pkgName); - break; + return { command: "npm", args: ["uninstall", pkgName] }; } - - return { command: this.activeCli, args }; } resolveInstallArgs(): { command: string; args: string[] } { @@ -72,26 +113,30 @@ export class NodeEngine extends BaseEngine { } resolveUpdateArgs(pkg?: PackageSpec): { command: string; args: string[] } { - const args: string[] = []; - const pkgTarget = pkg ? this.formatPackageTarget(pkg) : undefined; + const baseTarget = pkg ? this.formatBaseTarget(pkg) : undefined; switch (this.activeCli) { + case "deno": { + const args = ["outdated", "--update"]; + if (baseTarget) args.push(baseTarget); + return { command: "deno", args }; + } + case "yarn": { + const args = ["upgrade"]; + if (baseTarget) args.push(baseTarget); + return { command: "yarn", args }; + } case "pnpm": case "bun": - case "npm": - args.push("update"); - if (pkgTarget) args.push(pkgTarget); - break; - case "yarn": - args.push("upgrade"); - if (pkgTarget) args.push(pkgTarget); - break; + case "npm": { + const args = ["update"]; + if (baseTarget) args.push(baseTarget); + return { command: this.activeCli, args }; + } } - - return { command: this.activeCli, args }; } - private formatPackageTarget(pkg: PackageSpec): string { + private formatBaseTarget(pkg: PackageSpec): string { const base = pkg.namespace ? `${pkg.namespace}/${pkg.name}` : pkg.name; return pkg.version ? `${base}@${pkg.version}` : base; } diff --git a/src/engines/python.ts b/src/engines/python.ts index 42d3974..46e528c 100644 --- a/src/engines/python.ts +++ b/src/engines/python.ts @@ -1,82 +1,157 @@ -import type { PackageSpec } from "../types.js"; +import type { EngineContext, PackageSpec } from "../types.js"; import { BaseEngine } from "./base.js"; +export type PythonCli = "uv" | "poetry" | "pipenv" | "mamba" | "micromamba" | "conda" | "pip"; + +const PYTHON_CLIS = new Set([ + "uv", + "poetry", + "pipenv", + "mamba", + "micromamba", + "conda", + "pip", +]); + +function normalizeContext(preferred?: string | EngineContext): EngineContext { + if (!preferred) return {}; + if (typeof preferred === "string") return { lockfile: preferred }; + return preferred; +} + export class PythonEngine extends BaseEngine { readonly name = "python"; - readonly ecosystem = "pypi"; - private activeCli: "uv" | "poetry" | "pip"; + readonly ecosystem: string; + private readonly ctx: EngineContext; + private readonly activeCli: PythonCli; - constructor(preferredLockfile?: string) { + constructor(preferred?: string | EngineContext) { super(); - this.activeCli = this.detectActiveCli(preferredLockfile); + this.ctx = normalizeContext(preferred); + this.ecosystem = this.ctx.ecosystem ?? "pypi"; + this.activeCli = this.detectActiveCli(this.ctx); } - private detectActiveCli(lockfile?: string): "uv" | "poetry" | "pip" { + private isCondaManager(cli: PythonCli): cli is "conda" | "mamba" | "micromamba" { + return cli === "conda" || cli === "mamba" || cli === "micromamba"; + } + + private detectActiveCli(ctx: EngineContext): PythonCli { + if (ctx.preferredCli && PYTHON_CLIS.has(ctx.preferredCli)) { + return ctx.preferredCli as PythonCli; + } + + const { lockfile, manifest, ecosystem } = ctx; + + if ( + ecosystem === "conda" || + lockfile === "conda-lock.yml" || + manifest === "environment.yml" || + manifest === "environment.yaml" + ) { + if (this.isCommandAvailable("mamba")) return "mamba"; + if (this.isCommandAvailable("micromamba")) return "micromamba"; + return "conda"; + } + + if (lockfile === "Pipfile.lock" || manifest === "Pipfile") { + return "pipenv"; + } + if (lockfile === "uv.lock" && this.isCommandAvailable("uv")) return "uv"; if (lockfile === "poetry.lock" && this.isCommandAvailable("poetry")) return "poetry"; - // Fallback: prefer high-performance uv if available, else poetry, else pip if (this.isCommandAvailable("uv")) return "uv"; if (this.isCommandAvailable("poetry")) return "poetry"; + if (this.isCommandAvailable("pipenv")) return "pipenv"; return "pip"; } - getEffectiveCli(): string { + override getEffectiveCli(): string { return this.activeCli; } resolveAddArgs(pkg: PackageSpec): { command: string; args: string[] } { - const pkgTarget = this.formatPackageTarget(pkg); - const args: string[] = []; + const cli = this.activeCli; + if (this.isCondaManager(cli)) { + return { + command: cli, + args: ["install", "-y", this.formatPackageTarget(pkg, "=")], + }; + } - switch (this.activeCli) { - case "uv": - args.push("add", pkgTarget); + const pkgTarget = this.formatPackageTarget(pkg, "=="); + switch (cli) { + case "uv": { + const args = ["add", pkgTarget]; if (pkg.isDev) args.push("--dev"); - break; - case "poetry": - args.push("add", pkgTarget); + return { command: "uv", args }; + } + case "poetry": { + const args = ["add", pkgTarget]; if (pkg.isDev) args.push("--group", "dev"); - break; + return { command: "poetry", args }; + } + case "pipenv": { + const args = ["install", pkgTarget]; + if (pkg.isDev) args.push("--dev"); + return { command: "pipenv", args }; + } case "pip": - args.push("install", pkgTarget); - break; + return { command: "pip", args: ["install", pkgTarget] }; } - - return { command: this.activeCli, args }; } resolveRemoveArgs(pkg: PackageSpec): { command: string; args: string[] } { - const args: string[] = []; + const cli = this.activeCli; + if (this.isCondaManager(cli)) { + return { command: cli, args: ["remove", "-y", pkg.name] }; + } - switch (this.activeCli) { + switch (cli) { case "uv": - args.push("remove", pkg.name); - break; + return { command: "uv", args: ["remove", pkg.name] }; case "poetry": - args.push("remove", pkg.name); - break; + return { command: "poetry", args: ["remove", pkg.name] }; + case "pipenv": + return { command: "pipenv", args: ["uninstall", pkg.name] }; case "pip": - args.push("uninstall", "-y", pkg.name); - break; + return { command: "pip", args: ["uninstall", "-y", pkg.name] }; } - - return { command: this.activeCli, args }; } resolveInstallArgs(): { command: string; args: string[] } { - switch (this.activeCli) { + const cli = this.activeCli; + if (this.isCondaManager(cli)) { + const envFile = this.ctx.manifest || "environment.yml"; + return { command: cli, args: ["env", "update", "-f", envFile, "--prune"] }; + } + + switch (cli) { case "uv": return { command: "uv", args: ["sync"] }; case "poetry": return { command: "poetry", args: ["install"] }; + case "pipenv": + return { + command: "pipenv", + args: [this.ctx.lockfile === "Pipfile.lock" ? "sync" : "install"], + }; case "pip": return { command: "pip", args: ["install", "-r", "requirements.txt"] }; } } resolveUpdateArgs(pkg?: PackageSpec): { command: string; args: string[] } { - switch (this.activeCli) { + const cli = this.activeCli; + if (this.isCondaManager(cli)) { + const args = ["update", "-y"]; + if (pkg) args.push(this.formatPackageTarget(pkg, "=")); + else args.push("--all"); + return { command: cli, args }; + } + + switch (cli) { case "uv": return { command: "uv", @@ -87,22 +162,26 @@ export class PythonEngine extends BaseEngine { command: "poetry", args: pkg ? ["update", pkg.name] : ["update"], }; + case "pipenv": + return { + command: "pipenv", + args: pkg ? ["update", pkg.name] : ["update"], + }; case "pip": return { command: "pip", args: pkg - ? ["install", "--upgrade", this.formatPackageTarget(pkg)] + ? ["install", "--upgrade", this.formatPackageTarget(pkg, "==")] : ["install", "--upgrade", "-r", "requirements.txt"], }; } } - private formatPackageTarget(pkg: PackageSpec): string { + private formatPackageTarget(pkg: PackageSpec, eqOp: "==" | "="): string { if (!pkg.version) return pkg.name; - // Check if version already has an operator like >=, <=, == - if (/^[<>=~^]/.test(pkg.version)) { + if (/^[<>=~^!]/.test(pkg.version)) { return `${pkg.name}${pkg.version}`; } - return `${pkg.name}==${pkg.version}`; + return `${pkg.name}${eqOp}${pkg.version}`; } } diff --git a/src/engines/registry.ts b/src/engines/registry.ts new file mode 100644 index 0000000..fda1869 --- /dev/null +++ b/src/engines/registry.ts @@ -0,0 +1,314 @@ +import fs from "node:fs"; +import type { Ecosystem, EngineContext, PackageSpec } from "../types.js"; +import type { BaseEngine } from "./base.js"; +import { type EngineAdapter, defineDeclarativeAdapter } from "./declarative.js"; +import { GoEngine } from "./go.js"; +import { NodeEngine } from "./node.js"; +import { PythonEngine } from "./python.js"; +import { RustEngine } from "./rust.js"; + +/** + * Central extensible EngineAdapter registry powering detection, PURL parsing, + * native command dispatch, OSV compliance mapping, and private registry injection. + */ +export class EngineRegistry { + private adapters = new Map(); + private aliasIndex = new Map(); + private purlIndex = new Map(); + + register(adapter: EngineAdapter): void { + const key = adapter.ecosystem.toLowerCase(); + this.adapters.set(key, adapter); + this.aliasIndex.set(key, adapter.ecosystem); + this.purlIndex.set(key, adapter.ecosystem); + + for (const alias of adapter.aliases ?? []) { + this.aliasIndex.set(alias.toLowerCase(), adapter.ecosystem); + } + for (const purlType of adapter.purlTypes ?? []) { + this.purlIndex.set(purlType.toLowerCase(), adapter.ecosystem); + } + } + + unregister(ecosystem: string): boolean { + const key = ecosystem.toLowerCase(); + const existing = this.adapters.get(key); + if (!existing) return false; + + this.adapters.delete(key); + this.aliasIndex.delete(key); + this.purlIndex.delete(key); + + for (const alias of existing.aliases ?? []) { + if (this.aliasIndex.get(alias.toLowerCase()) === existing.ecosystem) { + this.aliasIndex.delete(alias.toLowerCase()); + } + } + for (const purlType of existing.purlTypes ?? []) { + if (this.purlIndex.get(purlType.toLowerCase()) === existing.ecosystem) { + this.purlIndex.delete(purlType.toLowerCase()); + } + } + return true; + } + + resolveEcosystem(token: string): Ecosystem | undefined { + return this.aliasIndex.get(token.trim().toLowerCase()); + } + + resolvePurlType(purlType: string): Ecosystem | undefined { + return this.purlIndex.get(purlType.trim().toLowerCase()); + } + + getAdapter(ecosystemOrAlias: string): EngineAdapter | undefined { + const resolved = this.resolveEcosystem(ecosystemOrAlias); + if (!resolved) return undefined; + return this.adapters.get(resolved.toLowerCase()); + } + + getAdapters(): EngineAdapter[] { + return Array.from(this.adapters.values()); + } + + listEcosystems(): Ecosystem[] { + return this.getAdapters().map((a) => a.ecosystem); + } + + isSupported(ecosystemOrAlias: string): boolean { + return this.getAdapter(ecosystemOrAlias) !== undefined; + } + + createEngine(ecosystemOrAlias: string, ctx?: EngineContext): BaseEngine { + const adapter = this.getAdapter(ecosystemOrAlias); + if (!adapter) { + throw new Error( + `Unsupported ecosystem '${ecosystemOrAlias}'. Registered ecosystems: ${this.listEcosystems().join(", ")}`, + ); + } + return adapter.createEngine({ ...ctx, ecosystem: adapter.ecosystem }); + } + + getOsvEcosystem(ecosystem: string): string | undefined { + return this.getAdapter(ecosystem)?.osvEcosystem; + } + + getSbomPurlType(ecosystem: string): string { + const adapter = this.getAdapter(ecosystem); + return adapter?.sbomPurlType ?? adapter?.purlTypes?.[0] ?? ecosystem; + } +} + +export const engineRegistry = new EngineRegistry(); + +// Built-in Ecosystem Adapters (Node/npm, Deno/JSR, Python/PyPI, Conda, Rust/Cargo, Go) +const npmAdapter: EngineAdapter = { + id: "node", + ecosystem: "npm", + aliases: ["node"], + purlTypes: ["npm"], + manifests: ["package.json"], + lockfiles: ["pnpm-lock.yaml", "bun.lockb", "bun.lock", "yarn.lock", "package-lock.json"], + osvEcosystem: "npm", + sbomPurlType: "npm", + defaultCli: "npm", + supportedClis: ["pnpm", "bun", "yarn", "npm", "deno"], + createEngine: (ctx) => new NodeEngine(ctx), + resolveScriptCommand: (script) => ["npm", ["run", script]], + injectRegistryEnv: (endpoint, env) => { + env.NPM_CONFIG_REGISTRY = endpoint.url; + env.npm_config_registry = endpoint.url; + if (endpoint.caFile) env.NPM_CONFIG_CAFILE = endpoint.caFile; + }, + injectRegistryFlags: (endpoint, args) => { + if (!args.includes("--registry")) { + args.push("--registry", endpoint.url); + } + }, + injectSandboxFlags: (_command, args) => { + const modified = [...args]; + if (!modified.includes("--ignore-scripts")) { + modified.push("--ignore-scripts"); + } + return modified; + }, + resolveEphemeralCommand: (spec, trailingArgs, commandExists) => { + const base = spec.namespace ? `${spec.namespace}/${spec.name}` : spec.name; + const fullPkg = spec.version ? `${base}@${spec.version}` : base; + if (commandExists("bun")) { + return { command: "bunx", args: [fullPkg, ...trailingArgs] }; + } + return { command: "npx", args: ["--yes", fullPkg, ...trailingArgs] }; + }, +}; + +const jsrAdapter: EngineAdapter = { + id: "deno", + ecosystem: "jsr", + aliases: ["deno"], + purlTypes: ["jsr"], + manifests: ["deno.json", "deno.jsonc"], + lockfiles: ["deno.lock"], + osvEcosystem: "npm", + sbomPurlType: "jsr", + defaultCli: "deno", + supportedClis: ["deno", "pnpm", "bun", "npm", "yarn"], + createEngine: (ctx) => new NodeEngine({ ...ctx, ecosystem: "jsr" }), + resolveScriptCommand: (script) => ["deno", ["task", script]], + injectSandboxFlags: (command, args) => { + if (command !== "deno") { + const modified = [...args]; + if (!modified.includes("--ignore-scripts")) modified.push("--ignore-scripts"); + return modified; + } + return args; + }, + resolveEphemeralCommand: (spec, trailingArgs, commandExists) => { + const base = spec.namespace ? `${spec.namespace}/${spec.name}` : spec.name; + const fullPkg = spec.version ? `${base}@${spec.version}` : base; + if (commandExists("deno")) { + return { command: "deno", args: ["run", `jsr:${fullPkg}`, ...trailingArgs] }; + } + return { command: "npx", args: ["--yes", "jsr", "run", fullPkg, ...trailingArgs] }; + }, +}; + +const pypiAdapter: EngineAdapter = { + id: "python", + ecosystem: "pypi", + aliases: ["python", "pip", "pipenv", "uv", "poetry"], + purlTypes: ["pypi"], + manifests: ["pyproject.toml", "requirements.txt", "Pipfile", "setup.py"], + lockfiles: ["uv.lock", "poetry.lock", "Pipfile.lock"], + osvEcosystem: "PyPI", + sbomPurlType: "pypi", + defaultCli: "uv", + supportedClis: ["uv", "poetry", "pipenv", "pip"], + createEngine: (ctx) => new PythonEngine(ctx), + resolveScriptCommand: (script) => ["python", ["-m", script]], + injectRegistryEnv: (endpoint, env) => { + env.UV_INDEX_URL = endpoint.url; + env.PIP_INDEX_URL = endpoint.url; + if (endpoint.trustedHost) env.PIP_TRUSTED_HOST = endpoint.trustedHost; + }, + injectRegistryFlags: (endpoint, args) => { + if (!args.includes("--index-url")) { + args.push("--index-url", endpoint.url); + } + }, + injectSandboxFlags: (command, args) => { + if (command === "pip" && !args.includes("--no-build-isolation")) { + return [...args, "--no-build-isolation"]; + } + return args; + }, +}; + +const condaAdapter: EngineAdapter = { + id: "conda", + ecosystem: "conda", + aliases: ["anaconda", "mamba", "micromamba"], + purlTypes: ["conda"], + manifests: ["environment.yml", "environment.yaml"], + lockfiles: ["conda-lock.yml"], + osvEcosystem: undefined, + sbomPurlType: "conda", + defaultCli: "conda", + supportedClis: ["mamba", "micromamba", "conda"], + createEngine: (ctx) => new PythonEngine({ ...ctx, ecosystem: "conda" }), + resolveScriptCommand: (script) => [ + "conda", + ["run", "--no-capture-output", "python", "-m", script], + ], + injectRegistryEnv: (endpoint, env) => { + env.CONDA_CHANNELS = endpoint.url; + }, + resolveEphemeralCommand: (spec, trailingArgs, commandExists) => { + const runner = commandExists("mamba") ? "mamba" : commandExists("conda") ? "conda" : null; + if (!runner) return null; + return { + command: runner, + args: ["run", spec.name, ...trailingArgs], + }; + }, +}; + +const cargoAdapter: EngineAdapter = { + id: "rust", + ecosystem: "cargo", + aliases: ["rust"], + purlTypes: ["cargo"], + manifests: ["Cargo.toml"], + lockfiles: ["Cargo.lock"], + osvEcosystem: "crates.io", + sbomPurlType: "cargo", + defaultCli: "cargo", + supportedClis: ["cargo"], + createEngine: () => new RustEngine(), + resolveScriptCommand: (script) => { + if (script === "dev" || script === "start") return ["cargo", ["run"]]; + if (script === "test") return ["cargo", ["test"]]; + return ["cargo", [script]]; + }, + injectRegistryEnv: (endpoint, env) => { + env.CARGO_REGISTRIES_CRATES_IO_INDEX = endpoint.url; + }, +}; + +const goAdapter: EngineAdapter = { + id: "go", + ecosystem: "go", + aliases: ["golang"], + purlTypes: ["golang", "go"], + manifests: ["go.mod"], + lockfiles: ["go.sum"], + osvEcosystem: "Go", + sbomPurlType: "golang", + defaultCli: "go", + supportedClis: ["go"], + createEngine: () => new GoEngine(), + resolveScriptCommand: (script) => { + if (script === "dev" || script === "start") return ["go", ["run", "."]]; + if (script === "test") return ["go", ["test", "./..."]]; + return ["go", [script]]; + }, + injectRegistryEnv: (endpoint, env) => { + env.GOPROXY = endpoint.url; + }, + resolveEphemeralCommand: (spec, trailingArgs) => { + const target = spec.version ? `${spec.name}@${spec.version}` : `${spec.name}@latest`; + return { command: "go", args: ["run", target, ...trailingArgs] }; + }, +}; + +engineRegistry.register(npmAdapter); +engineRegistry.register(jsrAdapter); +engineRegistry.register(pypiAdapter); +engineRegistry.register(condaAdapter); +engineRegistry.register(cargoAdapter); +engineRegistry.register(goAdapter); + +/** Ensures a PackageSpec target cleanly detects its first existing manifest file in cwd if missing. */ +export function resolveEcosystemLockContext(ecosystem: Ecosystem, cwd: string): EngineContext { + const adapter = engineRegistry.getAdapter(ecosystem); + if (!adapter) return { cwd, ecosystem }; + + let manifest: string | undefined; + let lockfile: string | undefined; + + for (const m of adapter.manifests) { + if (!m.includes("*") && !m.includes("?") && fs.existsSync(`${cwd}/${m}`)) { + manifest = m; + break; + } + } + for (const l of adapter.lockfiles) { + if (fs.existsSync(`${cwd}/${l}`)) { + lockfile = l; + break; + } + } + + return { cwd, ecosystem: adapter.ecosystem, manifest, lockfile }; +} + +export { defineDeclarativeAdapter }; diff --git a/src/purl/parser.ts b/src/purl/parser.ts index d88a753..9b63aa9 100644 --- a/src/purl/parser.ts +++ b/src/purl/parser.ts @@ -1,14 +1,9 @@ +import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem, PackageSpec } from "../types.js"; /** * Parses shorthand ecosystem tokens, standard Package URLs (PURL), or bare package strings. - * Examples: - * - "npm:axios" - * - "pypi:fastapi@^0.110.0" - * - "cargo:tokio@1.38.0" - * - "go:github.com/gin-gonic/gin@v1.9.1" - * - "pkg:npm/%40ritualdev-lab/agentshield@0.2.2" - * - "requests" + * Supported prefixes are resolved dynamically from EngineRegistry (e.g. npm:, jsr:, pypi:, conda:, cargo:, go:). */ export function parsePackageSpec(input: string, options?: { isDev?: boolean }): PackageSpec { const trimmed = input.trim(); @@ -16,29 +11,31 @@ export function parsePackageSpec(input: string, options?: { isDev?: boolean }): throw new Error("Cannot parse an empty package specification."); } - // 1. Check for standard Package URL: pkg://@ + // 1. Standard Package URL: pkg://@ if (trimmed.startsWith("pkg:")) { return parseStandardPurl(trimmed, options?.isDev); } - // 2. Check for shorthand ecosystem prefix: :[@] - const prefixMatch = trimmed.match(/^(npm|pypi|cargo|go):(.*)$/i); + // 2. Shorthand ecosystem prefix: :[@] + const prefixMatch = trimmed.match(/^([a-z0-9][a-z0-9_-]*):(.*)$/i); if (prefixMatch) { - const rawEcosystem = prefixMatch[1].toLowerCase() as Ecosystem; - const rest = prefixMatch[2]; - const { namespace, name, version } = parseNameAndVersion(rest); + const resolvedEcosystem = engineRegistry.resolveEcosystem(prefixMatch[1]); + if (resolvedEcosystem) { + const rest = prefixMatch[2]; + const { namespace, name, version } = parseNameAndVersion(rest); - return { - raw: trimmed, - ecosystem: rawEcosystem, - namespace, - name, - version, - isDev: options?.isDev ?? false, - }; + return { + raw: trimmed, + ecosystem: resolvedEcosystem, + namespace, + name, + version, + isDev: options?.isDev ?? false, + }; + } } - // 3. Bare package specification (ecosystem will be resolved via context detection) + // 3. Bare package specification (ecosystem resolved via context detection) const { namespace, name, version } = parseNameAndVersion(trimmed); return { raw: trimmed, @@ -61,7 +58,6 @@ function parseNameAndVersion(input: string): { let target = input; let namespace: string | undefined; - // Handle npm scoped packages like @ritualdev-lab/agentshield if (target.startsWith("@")) { const slashIdx = target.indexOf("/"); if (slashIdx !== -1) { @@ -70,7 +66,6 @@ function parseNameAndVersion(input: string): { } } - // Handle version separator @ const atIdx = target.indexOf("@"); if (atIdx !== -1) { const name = target.substring(0, atIdx); @@ -82,7 +77,7 @@ function parseNameAndVersion(input: string): { } /** - * Parses official Package URL format (RFC spec) + * Parses official Package URL format (RFC spec) using registered PURL types */ function parseStandardPurl(purl: string, isDev?: boolean): PackageSpec { const withoutScheme = purl.substring(4); // remove 'pkg:' @@ -92,23 +87,9 @@ function parseStandardPurl(purl: string, isDev?: boolean): PackageSpec { } const rawType = withoutScheme.substring(0, slashIdx).toLowerCase(); - let ecosystem: Ecosystem; - switch (rawType) { - case "npm": - ecosystem = "npm"; - break; - case "pypi": - ecosystem = "pypi"; - break; - case "cargo": - ecosystem = "cargo"; - break; - case "golang": - case "go": - ecosystem = "go"; - break; - default: - throw new Error(`Unsupported PURL ecosystem type '${rawType}' in '${purl}'.`); + const ecosystem: Ecosystem | undefined = engineRegistry.resolvePurlType(rawType); + if (!ecosystem) { + throw new Error(`Unsupported PURL ecosystem type '${rawType}' in '${purl}'.`); } const rest = decodeURIComponent(withoutScheme.substring(slashIdx + 1)); diff --git a/src/registry/router.ts b/src/registry/router.ts index f891c3a..a0af6d9 100644 --- a/src/registry/router.ts +++ b/src/registry/router.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem } from "../types.js"; import type { CorporateRegistryConfig, RegistryEndpoint } from "./types.js"; @@ -23,15 +24,19 @@ export class RegistryRouter { if (process.env.POLY_GO_PROXY && process.env.POLY_GO_PROXY !== "undefined") { config.go = { url: process.env.POLY_GO_PROXY }; } + if (process.env.POLY_CONDA_CHANNELS && process.env.POLY_CONDA_CHANNELS !== "undefined") { + config.conda = { url: process.env.POLY_CONDA_CHANNELS }; + } - // 2. Read poly.toml [registries] section + // 2. Read poly.toml [registries.] section const tomlPath = path.join(workspaceDir, "poly.toml"); if (fs.existsSync(tomlPath)) { const parsed = this.parseRegistriesFromToml(fs.readFileSync(tomlPath, "utf-8")); - if (parsed.npm && !config.npm) config.npm = parsed.npm; - if (parsed.pypi && !config.pypi) config.pypi = parsed.pypi; - if (parsed.cargo && !config.cargo) config.cargo = parsed.cargo; - if (parsed.go && !config.go) config.go = parsed.go; + for (const [eco, endpoint] of Object.entries(parsed)) { + if (endpoint && !config[eco]) { + config[eco] = endpoint; + } + } } return config; @@ -47,43 +52,11 @@ export class RegistryRouter { ): NodeJS.ProcessEnv { const registries = this.loadRegistryConfig(workspaceDir); const env = { ...existingEnv }; + const endpoint = registries[ecosystem]; + const adapter = engineRegistry.getAdapter(ecosystem); - switch (ecosystem) { - case "npm": { - if (registries.npm?.url) { - env.NPM_CONFIG_REGISTRY = registries.npm.url; - env.npm_config_registry = registries.npm.url; - } - if (registries.npm?.caFile) { - env.NPM_CONFIG_CAFILE = registries.npm.caFile; - } - break; - } - - case "pypi": { - if (registries.pypi?.url) { - env.UV_INDEX_URL = registries.pypi.url; - env.PIP_INDEX_URL = registries.pypi.url; - } - if (registries.pypi?.trustedHost) { - env.PIP_TRUSTED_HOST = registries.pypi.trustedHost; - } - break; - } - - case "go": { - if (registries.go?.url) { - env.GOPROXY = registries.go.url; - } - break; - } - - case "cargo": { - if (registries.cargo?.url) { - env.CARGO_REGISTRIES_CRATES_IO_INDEX = registries.cargo.url; - } - break; - } + if (endpoint && adapter?.injectRegistryEnv) { + adapter.injectRegistryEnv(endpoint, env); } return env; @@ -95,21 +68,11 @@ export class RegistryRouter { injectCliFlags(ecosystem: Ecosystem, baseArgs: string[], workspaceDir: string): string[] { const registries = this.loadRegistryConfig(workspaceDir); const args = [...baseArgs]; + const endpoint = registries[ecosystem]; + const adapter = engineRegistry.getAdapter(ecosystem); - switch (ecosystem) { - case "npm": { - if (registries.npm?.url && !args.includes("--registry")) { - args.push("--registry", registries.npm.url); - } - break; - } - - case "pypi": { - if (registries.pypi?.url && !args.includes("--index-url")) { - args.push("--index-url", registries.pypi.url); - } - break; - } + if (endpoint && adapter?.injectRegistryFlags) { + adapter.injectRegistryFlags(endpoint, args); } return args; @@ -124,11 +87,14 @@ export class RegistryRouter { const line = raw.trim(); if (!line || line.startsWith("#")) continue; - if (line === "[registries.npm]") currentEco = "npm"; - else if (line === "[registries.pypi]") currentEco = "pypi"; - else if (line === "[registries.cargo]") currentEco = "cargo"; - else if (line === "[registries.go]") currentEco = "go"; - else if (line.startsWith("[")) currentEco = undefined; + const regHeader = line.match(/^\[registries\.([a-z0-9_-]+)\]$/i); + if (regHeader) { + currentEco = engineRegistry.resolveEcosystem(regHeader[1]) ?? regHeader[1].toLowerCase(); + continue; + } + if (line.startsWith("[")) { + currentEco = undefined; + } if (!currentEco) continue; diff --git a/src/registry/types.ts b/src/registry/types.ts index 5d6f7eb..f599252 100644 --- a/src/registry/types.ts +++ b/src/registry/types.ts @@ -12,6 +12,7 @@ export interface CorporateRegistryConfig { pypi?: RegistryEndpoint; cargo?: RegistryEndpoint; go?: RegistryEndpoint; + [ecosystem: string]: RegistryEndpoint | undefined; } export interface RegistryHealthStatus { diff --git a/src/sandbox/enforcer.ts b/src/sandbox/enforcer.ts index 7f9deaa..9ee55fb 100644 --- a/src/sandbox/enforcer.ts +++ b/src/sandbox/enforcer.ts @@ -1,3 +1,4 @@ +import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem, PackageSpec } from "../types.js"; import { scanPackageLifecycleScripts } from "./scanner.js"; import type { SandboxScanResult } from "./types.js"; @@ -23,32 +24,12 @@ export function injectSandboxFlags( const isAllowed = pkgName && options.allowScripts?.includes(pkgName); if (isAllowed) return args; - const modified = [...args]; - - switch (ecosystem) { - case "npm": { - // For pnpm, npm, bun, yarn: inject --ignore-scripts - if (!modified.includes("--ignore-scripts")) { - modified.push("--ignore-scripts"); - } - break; - } - - case "pypi": { - // For pip or uv: disallow arbitrary build-time execution - if (command === "pip" && !modified.includes("--no-build-isolation")) { - modified.push("--no-build-isolation"); - } - break; - } - - case "cargo": - case "go": - // Cargo and Go compile standard dependency trees without arbitrary pre/post install scripts - break; + const adapter = engineRegistry.getAdapter(ecosystem); + if (adapter?.injectSandboxFlags) { + return adapter.injectSandboxFlags(command, args); } - return modified; + return [...args]; } /** diff --git a/src/sandbox/try.ts b/src/sandbox/try.ts index 9c3bb02..38a99cc 100644 --- a/src/sandbox/try.ts +++ b/src/sandbox/try.ts @@ -2,6 +2,7 @@ import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { engineRegistry } from "../engines/registry.js"; import { parsePackageSpec } from "../purl/parser.js"; import type { Ecosystem } from "../types.js"; import { logError, logHeader, logInfo } from "../ui/reporter.js"; @@ -91,12 +92,13 @@ export async function runEphemeralTry( logInfo(`Provisioning ${fullPkg} (${ecosystem}) in zero-footprint sandbox...`); } - // 1. Node.js Ecosystem: prefer bunx -> fallback npx --yes - if (ecosystem === "npm") { - const hasBun = commandExists("bun"); - const cmd = hasBun ? "bunx" : "npx"; - const cmdArgs = hasBun ? [fullPkg, ...trailingArgs] : ["--yes", fullPkg, ...trailingArgs]; - return executeEphemeral(cmd, cmdArgs); + // Delegate ecosystems registering an ephemeral runner (npm, jsr, conda, go, etc.) + const adapter = engineRegistry.getAdapter(ecosystem); + if (adapter?.resolveEphemeralCommand) { + const resolved = adapter.resolveEphemeralCommand(spec, trailingArgs, commandExists); + if (resolved) { + return executeEphemeral(resolved.command, resolved.args); + } } // 2. Python Ecosystem: prefer uvx -> fallback pipx run -> fallback temp venv diff --git a/src/types.ts b/src/types.ts index 0601220..9ed67c7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,7 +3,16 @@ * Universal Package & Dependency Orchestration Specification */ -export type Ecosystem = "npm" | "pypi" | "cargo" | "go"; +export type BuiltinEcosystem = "npm" | "jsr" | "pypi" | "conda" | "cargo" | "go"; +export type Ecosystem = BuiltinEcosystem | (string & {}); + +export interface EngineContext { + cwd?: string; + manifest?: string; + lockfile?: string; + ecosystem?: Ecosystem; + preferredCli?: string; +} export interface PackageSpec { raw: string; @@ -66,7 +75,10 @@ export interface WorkspaceConfig { node?: string; rust?: string; go?: string; + deno?: string; + conda?: string; concurrency?: number; + [key: string]: string | number | undefined; }; tasks?: Record; scripts?: Record; diff --git a/src/workspace/crypto.ts b/src/workspace/crypto.ts index f6af776..65ed1fa 100644 --- a/src/workspace/crypto.ts +++ b/src/workspace/crypto.ts @@ -46,9 +46,59 @@ export function extractDirectDependencies(manifestPath: string, ecosystem: Ecosy break; } + case "jsr": { + // Parse deno.json / deno.jsonc imports map (jsr:@std/path@^1.0.0, npm:zod@^3.22.0) + try { + const cleanJson = content.replace(/^\s*\/\/.*$/gm, ""); + const parsed = JSON.parse(cleanJson) as { imports?: Record }; + for (const target of Object.values(parsed.imports ?? {})) { + if ( + typeof target === "string" && + (target.startsWith("jsr:") || target.startsWith("npm:")) + ) { + deps.push(target); + } + } + } catch { + // Ignore malformed deno.json/jsonc + } + break; + } + case "pypi": { - // Parse dependencies = [ "fastapi>=0.110.0", ... ] in pyproject.toml or requirements.txt + const fileName = path.basename(manifestPath); const lines = content.split("\n"); + + if (fileName === "Pipfile") { + let inPackages = false; + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed === "[packages]" || trimmed === "[dev-packages]") { + inPackages = true; + continue; + } + if (trimmed.startsWith("[")) { + inPackages = false; + continue; + } + if (inPackages && trimmed && !trimmed.startsWith("#")) { + const eqIdx = trimmed.indexOf("="); + if (eqIdx !== -1) { + const name = trimmed.substring(0, eqIdx).trim().replace(/["']/g, ""); + const rawVer = trimmed + .substring(eqIdx + 1) + .trim() + .replace(/["']/g, ""); + if (name) { + deps.push(rawVer && rawVer !== "*" ? `pypi:${name}${rawVer}` : `pypi:${name}`); + } + } + } + } + break; + } + + // Parse dependencies = [ "fastapi>=0.110.0", ... ] in pyproject.toml or requirements.txt let inDepsSection = false; for (const line of lines) { @@ -66,17 +116,59 @@ export function extractDirectDependencies(manifestPath: string, ecosystem: Ecosy if (clean && !clean.startsWith("#")) { deps.push(`pypi:${clean}`); } - } else if ( - path.basename(manifestPath) === "requirements.txt" && - trimmed && - !trimmed.startsWith("#") - ) { + } else if (fileName === "requirements.txt" && trimmed && !trimmed.startsWith("#")) { deps.push(`pypi:${trimmed}`); } } break; } + case "conda": { + // Parse environment.yml dependencies: (- numpy=1.26.4, nested pip: items) + const lines = content.split("\n"); + let inDeps = false; + let inPip = false; + + for (const rawLine of lines) { + const trimmed = rawLine.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + + if (trimmed === "dependencies:") { + inDeps = true; + inPip = false; + continue; + } + if ( + inDeps && + !rawLine.startsWith(" ") && + !rawLine.startsWith("-") && + trimmed.endsWith(":") + ) { + inDeps = false; + inPip = false; + continue; + } + if (!inDeps) continue; + + if (trimmed === "- pip:" || trimmed === "pip:") { + inPip = true; + continue; + } + if (trimmed.startsWith("- ")) { + const item = trimmed.slice(2).trim().replace(/["']/g, ""); + if (!item) continue; + const indent = rawLine.search(/\S|$/); + if (inPip && indent >= 4) { + deps.push(`pypi:${item}`); + } else { + inPip = false; + deps.push(`conda:${item}`); + } + } + } + break; + } + case "cargo": { // Parse [dependencies] section in Cargo.toml const lines = content.split("\n"); diff --git a/src/workspace/dispatcher.ts b/src/workspace/dispatcher.ts index ac54d89..7da9d06 100644 --- a/src/workspace/dispatcher.ts +++ b/src/workspace/dispatcher.ts @@ -1,4 +1,4 @@ -import { GoEngine, NodeEngine, PythonEngine, RustEngine } from "../engines/index.js"; +import { engineRegistry } from "../engines/index.js"; import { RegistryRouter } from "../registry/index.js"; import type { Ecosystem, ExecutionResult } from "../types.js"; import { loadWorkspaceConfig, resolveWorkspaceMembers } from "./config.js"; @@ -45,7 +45,12 @@ export class WorkspaceDispatcher { const member = queue.shift(); if (!member) break; const workerPromise = (async () => { - const engine = this.getEngine(member.context.ecosystem, member.context.lockfile); + const engine = this.getEngine( + member.context.ecosystem, + member.context.manifestFile, + member.context.lockfile, + member.absoluteDir, + ); const { command, args } = engine.resolveInstallArgs(); const routedArgs = this.registryRouter.injectCliFlags( member.context.ecosystem, @@ -83,16 +88,7 @@ export class WorkspaceDispatcher { return results; } - private getEngine(ecosystem: Ecosystem, lockfile?: string) { - switch (ecosystem) { - case "npm": - return new NodeEngine(lockfile); - case "pypi": - return new PythonEngine(lockfile); - case "cargo": - return new RustEngine(); - case "go": - return new GoEngine(); - } + private getEngine(ecosystem: Ecosystem, manifest?: string, lockfile?: string, cwd?: string) { + return engineRegistry.createEngine(ecosystem, { ecosystem, manifest, lockfile, cwd }); } } diff --git a/src/workspace/runner.ts b/src/workspace/runner.ts index c83a89a..6185c44 100644 --- a/src/workspace/runner.ts +++ b/src/workspace/runner.ts @@ -1,6 +1,7 @@ import { type ChildProcess, spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; +import { engineRegistry } from "../engines/registry.js"; import { type AffectedResult, resolveAffectedMembers } from "./affected.js"; import { type ResolvedMember, loadWorkspaceConfig, resolveWorkspaceMembers } from "./config.js"; @@ -456,29 +457,10 @@ export class WorkspaceRunner { } private resolveScriptCommand(ecosystem: string, script: string): [string, string[]] { - switch (ecosystem) { - case "npm": - return ["npm", ["run", script]]; - case "pypi": - return ["python", ["-m", script]]; - case "cargo": - if (script === "dev" || script === "start") { - return ["cargo", ["run"]]; - } - if (script === "test") { - return ["cargo", ["test"]]; - } - return ["cargo", [script]]; - case "go": - if (script === "dev" || script === "start") { - return ["go", ["run", "."]]; - } - if (script === "test") { - return ["go", ["test", "./..."]]; - } - return ["go", [script]]; - default: - return [script, []]; + const adapter = engineRegistry.getAdapter(ecosystem); + if (adapter?.resolveScriptCommand) { + return adapter.resolveScriptCommand(script); } + return [script, []]; } } diff --git a/tests/completion.test.ts b/tests/completion.test.ts index b326998..2211c4e 100644 --- a/tests/completion.test.ts +++ b/tests/completion.test.ts @@ -40,7 +40,7 @@ test("Shell Auto-Completion - Dynamic Resolution", async (t) => { await t.test("resolves ecosystems for which command", () => { const ecosystems = resolveDynamicCompletions("which"); - assert.deepEqual(ecosystems, ["npm", "pypi", "cargo", "go"]); + assert.deepEqual(ecosystems, ["npm", "jsr", "pypi", "conda", "cargo", "go"]); }); await t.test("resolves all CLI command names", () => { diff --git a/tests/engines.test.ts b/tests/engines.test.ts index 0343281..db4e80b 100644 --- a/tests/engines.test.ts +++ b/tests/engines.test.ts @@ -87,3 +87,109 @@ test("Go Engine - Resolves go get and go mod tidy", () => { const rmArgs = engine.resolveRemoveArgs(pkg); assert.deepEqual(rmArgs.args, ["mod", "tidy"]); }); + +test("Node Engine - Resolves Deno & JSR add/remove/install/update syntax", () => { + const denoEngine = new NodeEngine({ + manifest: "deno.json", + lockfile: "deno.lock", + ecosystem: "jsr", + preferredCli: "deno", + }); + assert.equal(denoEngine.getEffectiveCli(), "deno"); + + const jsrPkg: PackageSpec = { + raw: "jsr:@std/path@^1.0.0", + ecosystem: "jsr", + namespace: "@std", + name: "path", + version: "^1.0.0", + }; + assert.deepEqual(denoEngine.resolveAddArgs(jsrPkg), { + command: "deno", + args: ["add", "jsr:@std/path@^1.0.0"], + }); + assert.deepEqual(denoEngine.resolveRemoveArgs(jsrPkg), { + command: "deno", + args: ["remove", "@std/path"], + }); + assert.deepEqual(denoEngine.resolveInstallArgs(), { + command: "deno", + args: ["install"], + }); + assert.deepEqual(denoEngine.resolveUpdateArgs(jsrPkg), { + command: "deno", + args: ["outdated", "--update", "@std/path@^1.0.0"], + }); + + const npmPkgInDeno: PackageSpec = { + raw: "npm:zod@^3.22.4", + ecosystem: "npm", + name: "zod", + version: "^3.22.4", + }; + assert.deepEqual(denoEngine.resolveAddArgs(npmPkgInDeno), { + command: "deno", + args: ["add", "npm:zod@^3.22.4"], + }); + + const pnpmWithJsr = new NodeEngine({ lockfile: "pnpm-lock.yaml", preferredCli: "pnpm" }); + assert.deepEqual(pnpmWithJsr.resolveAddArgs(jsrPkg), { + command: "pnpm", + args: ["dlx", "jsr", "add", "@std/path@^1.0.0"], + }); +}); + +test("Python Engine - Resolves Pipenv & Conda add/remove/install/update syntax", () => { + const pipenvEngine = new PythonEngine({ manifest: "Pipfile", lockfile: "Pipfile.lock" }); + assert.equal(pipenvEngine.getEffectiveCli(), "pipenv"); + + const reqPkg: PackageSpec = { + raw: "pypi:requests@>=2.31.0", + ecosystem: "pypi", + name: "requests", + version: ">=2.31.0", + isDev: true, + }; + assert.deepEqual(pipenvEngine.resolveAddArgs(reqPkg), { + command: "pipenv", + args: ["install", "requests>=2.31.0", "--dev"], + }); + assert.deepEqual(pipenvEngine.resolveRemoveArgs(reqPkg), { + command: "pipenv", + args: ["uninstall", "requests"], + }); + assert.deepEqual(pipenvEngine.resolveInstallArgs(), { + command: "pipenv", + args: ["sync"], + }); + + const condaEngine = new PythonEngine({ + ecosystem: "conda", + manifest: "environment.yml", + preferredCli: "conda", + }); + assert.equal(condaEngine.getEffectiveCli(), "conda"); + + const condaPkg: PackageSpec = { + raw: "conda:numpy@1.26.4", + ecosystem: "conda", + name: "numpy", + version: "1.26.4", + }; + assert.deepEqual(condaEngine.resolveAddArgs(condaPkg), { + command: "conda", + args: ["install", "-y", "numpy=1.26.4"], + }); + assert.deepEqual(condaEngine.resolveRemoveArgs(condaPkg), { + command: "conda", + args: ["remove", "-y", "numpy"], + }); + assert.deepEqual(condaEngine.resolveInstallArgs(), { + command: "conda", + args: ["env", "update", "-f", "environment.yml", "--prune"], + }); + assert.deepEqual(condaEngine.resolveUpdateArgs(), { + command: "conda", + args: ["update", "-y", "--all"], + }); +}); diff --git a/tests/phase1-registry.test.ts b/tests/phase1-registry.test.ts new file mode 100644 index 0000000..dd52bb5 --- /dev/null +++ b/tests/phase1-registry.test.ts @@ -0,0 +1,171 @@ +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 { detectContexts, matchesManifestGlob } from "../src/detector/tree-walker.js"; +import { PolyDispatcher } from "../src/dispatcher/executor.js"; +import { PolyDoctor } from "../src/doctor/checker.js"; +import { defineDeclarativeAdapter, engineRegistry } from "../src/engines/index.js"; +import { parsePackageSpec } from "../src/purl/parser.js"; +import { verifyCompositeLockfile, writeCompositeLockfile } from "../src/workspace/lockfile.js"; + +test("Detector - Supports Deno, Pipenv, and Conda manifests & lockfiles", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase1-detect-")); + const denoDir = path.join(tmpDir, "deno-app"); + const pipenvDir = path.join(tmpDir, "pipenv-svc"); + const condaDir = path.join(tmpDir, "conda-ml"); + fs.mkdirSync(denoDir, { recursive: true }); + fs.mkdirSync(pipenvDir, { recursive: true }); + fs.mkdirSync(condaDir, { recursive: true }); + + try { + fs.writeFileSync(path.join(denoDir, "deno.json"), JSON.stringify({ imports: {} })); + fs.writeFileSync(path.join(denoDir, "deno.lock"), "{}"); + const denoCtx = detectContexts(denoDir); + assert.equal(denoCtx[0]?.ecosystem, "jsr"); + assert.equal(denoCtx[0]?.manifestFile, "deno.json"); + assert.equal(denoCtx[0]?.lockfile, "deno.lock"); + + fs.writeFileSync(path.join(pipenvDir, "Pipfile"), '[packages]\nrequests = "*"\n'); + fs.writeFileSync(path.join(pipenvDir, "Pipfile.lock"), "{}"); + const pipenvCtx = detectContexts(pipenvDir); + assert.equal(pipenvCtx[0]?.ecosystem, "pypi"); + assert.equal(pipenvCtx[0]?.manifestFile, "Pipfile"); + assert.equal(pipenvCtx[0]?.lockfile, "Pipfile.lock"); + + fs.writeFileSync( + path.join(condaDir, "environment.yml"), + "name: ml\ndependencies:\n - numpy=1.26.4\n", + ); + fs.writeFileSync(path.join(condaDir, "conda-lock.yml"), "version: 1\n"); + const condaCtx = detectContexts(condaDir); + assert.equal(condaCtx[0]?.ecosystem, "conda"); + assert.equal(condaCtx[0]?.manifestFile, "environment.yml"); + assert.equal(condaCtx[0]?.lockfile, "conda-lock.yml"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test("Detector - Glob matching handles *.csproj, *.rockspec, and *.cabal", () => { + assert.equal(matchesManifestGlob("MyService.csproj", "*.csproj"), true); + assert.equal(matchesManifestGlob("luafilesystem-1.8.0-1.rockspec", "*.rockspec"), true); + assert.equal(matchesManifestGlob("awesome-lib.cabal", "*.cabal"), true); + assert.equal(matchesManifestGlob("package.json", "*.csproj"), false); + + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase1-glob-")); + const nugetAdapter = defineDeclarativeAdapter({ + id: "dotnet-test", + ecosystem: "nuget", + purlTypes: ["nuget"], + manifests: ["*.csproj"], + lockfiles: ["packages.lock.json"], + commands: { + command: "dotnet", + add: (pkg) => ["add", "package", pkg.name], + remove: (pkg) => ["remove", "package", pkg.name], + install: () => ["restore"], + update: (pkg) => ["add", "package", pkg?.name ?? ""], + }, + }); + + try { + engineRegistry.register(nugetAdapter); + fs.writeFileSync(path.join(tmpDir, "BillingService.csproj"), ""); + + const contexts = detectContexts(tmpDir); + assert.equal(contexts.length, 1); + assert.equal(contexts[0].ecosystem, "nuget"); + assert.equal(contexts[0].manifestFile, "BillingService.csproj"); + + const spec = parsePackageSpec("nuget:Newtonsoft.Json@13.0.3"); + assert.equal(spec.ecosystem, "nuget"); + const engine = engineRegistry.createEngine("nuget"); + assert.deepEqual(engine.resolveAddArgs(spec), { + command: "dotnet", + args: ["add", "package", "Newtonsoft.Json"], + }); + } finally { + engineRegistry.unregister("nuget"); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test("Phase 1 Exit Gate - Dispatcher which, poly.lock, OSV audit & PolyDoctor across Deno, Pipenv, Conda", async () => { + const wsDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase1-ws-")); + const denoDir = path.join(wsDir, "apps", "edge"); + const pipenvDir = path.join(wsDir, "services", "api"); + const condaDir = path.join(wsDir, "services", "ml"); + + fs.mkdirSync(denoDir, { recursive: true }); + fs.mkdirSync(pipenvDir, { recursive: true }); + fs.mkdirSync(condaDir, { recursive: true }); + + fs.writeFileSync( + path.join(wsDir, "poly.toml"), + `[workspace]\nname = "phase1-demo"\nmembers = ["apps/*", "services/*"]\n`, + ); + + fs.writeFileSync( + path.join(denoDir, "deno.json"), + JSON.stringify({ + imports: { + "@std/path": "jsr:@std/path@^1.0.0", + zod: "npm:zod@^3.22.4", + }, + }), + ); + fs.writeFileSync(path.join(denoDir, "deno.lock"), "{}"); + + fs.writeFileSync( + path.join(pipenvDir, "Pipfile"), + `[packages]\nfastapi = ">=0.110.0"\n\n[dev-packages]\npytest = "*"\n`, + ); + fs.writeFileSync(path.join(pipenvDir, "Pipfile.lock"), "{}"); + + fs.writeFileSync( + path.join(condaDir, "environment.yml"), + "name: ml-env\ndependencies:\n - numpy=1.26.4\n - pip:\n - requests==2.31.0\n", + ); + + try { + const dispatcher = new PolyDispatcher(); + assert.equal(dispatcher.which("jsr", denoDir).effectiveCli, "deno"); + assert.equal(dispatcher.which("pypi", pipenvDir).effectiveCli, "pipenv"); + const condaWhich = dispatcher.which("conda", condaDir).effectiveCli; + assert.ok(["conda", "mamba", "micromamba"].includes(condaWhich)); + + // Verify poly.lock generation & zero-drift verification + const lock = writeCompositeLockfile(wsDir); + assert.equal(lock.members.length, 3); + const denoMember = lock.members.find((m) => m.ecosystem === "jsr"); + const condaMember = lock.members.find((m) => m.ecosystem === "conda"); + const pipenvMember = lock.members.find((m) => m.ecosystem === "pypi"); + + assert.ok(denoMember?.directDependencies.includes("jsr:@std/path@^1.0.0")); + assert.ok(denoMember?.directDependencies.includes("npm:zod@^3.22.4")); + assert.ok(pipenvMember?.directDependencies.includes("pypi:fastapi>=0.110.0")); + assert.ok(condaMember?.directDependencies.includes("conda:numpy=1.26.4")); + assert.ok(condaMember?.directDependencies.includes("pypi:requests==2.31.0")); + + const drift = verifyCompositeLockfile(wsDir); + assert.equal(drift.isDrifted, false); + + // Verify OSV auditor executes cleanly on composite workspace containing jsr/conda/pypi + const auditor = new CrossStackAuditor(); + const auditReport = await auditor.audit(wsDir); + assert.ok(auditReport.scannedPackages >= 5); + + // Verify PolyDoctor runs cleanly against polyglot workspace with poly.lock + const doctor = new PolyDoctor(); + const doctorReport = await doctor.diagnose(wsDir); + const lockCheck = doctorReport.checks.find((c) => c.id === "workspace-lock-drift"); + assert.equal(lockCheck?.status, "OK"); + assert.ok(doctorReport.checks.some((c) => c.id === "toolchain-node-managers")); + assert.ok(doctorReport.checks.some((c) => c.id === "toolchain-python-uv")); + } finally { + fs.rmSync(wsDir, { recursive: true, force: true }); + } +}); diff --git a/tests/purl.test.ts b/tests/purl.test.ts index e95ecd4..21527a6 100644 --- a/tests/purl.test.ts +++ b/tests/purl.test.ts @@ -24,6 +24,17 @@ test("PURL Parser - Shorthand Ecosystem Prefixes", () => { assert.equal(goPkg.ecosystem, "go"); assert.equal(goPkg.name, "github.com/gin-gonic/gin"); assert.equal(goPkg.version, "v1.9.1"); + + const jsrPkg = parsePackageSpec("jsr:@std/path@^1.0.0"); + assert.equal(jsrPkg.ecosystem, "jsr"); + assert.equal(jsrPkg.namespace, "@std"); + assert.equal(jsrPkg.name, "path"); + assert.equal(jsrPkg.version, "^1.0.0"); + + const condaPkg = parsePackageSpec("conda:numpy@1.26.4"); + assert.equal(condaPkg.ecosystem, "conda"); + assert.equal(condaPkg.name, "numpy"); + assert.equal(condaPkg.version, "1.26.4"); }); test("PURL Parser - Scoped Packages (@namespace/name)", () => { @@ -45,6 +56,17 @@ test("PURL Parser - Standard RFC Package URLs", () => { assert.equal(stdPypi.ecosystem, "pypi"); assert.equal(stdPypi.name, "requests"); assert.equal(stdPypi.version, "2.31.0"); + + const stdJsr = parsePackageSpec("pkg:jsr/%40std/path@1.0.8"); + assert.equal(stdJsr.ecosystem, "jsr"); + assert.equal(stdJsr.namespace, "@std"); + assert.equal(stdJsr.name, "path"); + assert.equal(stdJsr.version, "1.0.8"); + + const stdConda = parsePackageSpec("pkg:conda/numpy@1.26.4"); + assert.equal(stdConda.ecosystem, "conda"); + assert.equal(stdConda.name, "numpy"); + assert.equal(stdConda.version, "1.26.4"); }); test("PURL Parser - Bare Package Names (No prefix)", () => {