diff --git a/src/cli.ts b/src/cli.ts index 0007a7e..5f477e1 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, maven, gradle, sbt, hex, rebar3, swift, cocoapods, carthage) + 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, hackage, cran, cpan, luarocks) OPTIONS: -D, --dev Install as a development dependency @@ -1075,6 +1075,7 @@ async function main(): Promise { process.exit(1); } + await engineRegistry.ensureLoaded(resolved); const dispatcher = new PolyDispatcher(); const info = dispatcher.which(resolved, cwd); if (isJson) { diff --git a/src/detector/tree-walker.ts b/src/detector/tree-walker.ts index ac35936..05c4096 100644 --- a/src/detector/tree-walker.ts +++ b/src/detector/tree-walker.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import { syncCustomEnginesInDir } from "../engines/custom.js"; import { engineRegistry } from "../engines/registry.js"; import type { Ecosystem, ManifestContext } from "../types.js"; @@ -58,6 +59,7 @@ export function detectContexts(startDir: string): ManifestContext[] { const visitedEcosystems = new Set(); while (true) { + syncCustomEnginesInDir(current); let dirEntriesCache: string[] | undefined; for (const adapter of engineRegistry.getAdapters()) { diff --git a/src/dispatcher/executor.ts b/src/dispatcher/executor.ts index d23ae15..bfcf2b8 100644 --- a/src/dispatcher/executor.ts +++ b/src/dispatcher/executor.ts @@ -1,5 +1,6 @@ import { detectContexts, resolvePrimaryContext } from "../detector/tree-walker.js"; -import { type BaseEngine, engineRegistry } from "../engines/index.js"; +import type { BaseEngine } from "../engines/base.js"; +import { engineRegistry } from "../engines/registry.js"; import { parsePackageSpec } from "../purl/parser.js"; import { RegistryRouter } from "../registry/index.js"; import { evaluateSandboxGate, injectSandboxFlags } from "../sandbox/index.js"; @@ -62,7 +63,9 @@ export class PolyDispatcher { } } - // 3. Select native engine + // 3. Select native engine (lazy-loading only the needed ecosystem adapter) + await engineRegistry.ensureLoaded(pkg.ecosystem); + await engineRegistry.ensureLoaded(pkg.ecosystem); const engine = this.getEngineForEcosystem(pkg.ecosystem, cwd); const { command, args } = engine.resolveAddArgs(pkg); const routedArgs = this.registryRouter.injectCliFlags(pkg.ecosystem, args, cwd); @@ -107,6 +110,7 @@ export class PolyDispatcher { pkg.ecosystem = await this.resolveEcosystemForPackage(pkg.name, cwd); } + await engineRegistry.ensureLoaded(pkg.ecosystem); const engine = this.getEngineForEcosystem(pkg.ecosystem, cwd); const mutation = engine.applyManifestRemove?.(pkg, cwd); if (mutation?.changed && !options?.silent && !options?.agent) { @@ -141,6 +145,7 @@ export class PolyDispatcher { const results: ExecutionResult[] = []; for (const ctx of allContexts) { + await engineRegistry.ensureLoaded(ctx.ecosystem); const engine = this.getEngineForEcosystem(ctx.ecosystem, ctx.directory); const { command, args } = engine.resolveInstallArgs(); const routedArgs = this.registryRouter.injectCliFlags(ctx.ecosystem, args, ctx.directory); @@ -176,6 +181,7 @@ export class PolyDispatcher { throw new Error(`No project manifests found in '${cwd}' or parent directories.`); } + await engineRegistry.ensureLoaded(targetEcosystem); const engine = this.getEngineForEcosystem(targetEcosystem, cwd); const { command, args } = engine.resolveInstallArgs(); const routedArgs = this.registryRouter.injectCliFlags(targetEcosystem, args, cwd); @@ -209,6 +215,7 @@ export class PolyDispatcher { pkg.ecosystem = await this.resolveEcosystemForPackage(pkg.name, cwd, options?.agent); } + await engineRegistry.ensureLoaded(pkg.ecosystem); const engine = this.getEngineForEcosystem(pkg.ecosystem, cwd); const { command, args } = engine.resolveUpdateArgs(pkg); const routedArgs = this.registryRouter.injectCliFlags(pkg.ecosystem, args, cwd); @@ -243,6 +250,7 @@ export class PolyDispatcher { const results: ExecutionResult[] = []; for (const ctx of allContexts) { + await engineRegistry.ensureLoaded(ctx.ecosystem); const engine = this.getEngineForEcosystem(ctx.ecosystem, ctx.directory); const { command, args } = engine.resolveUpdateArgs(); const routedArgs = this.registryRouter.injectCliFlags(ctx.ecosystem, args, ctx.directory); @@ -278,6 +286,7 @@ export class PolyDispatcher { throw new Error(`No project manifests found in '${cwd}' or parent directories.`); } + await engineRegistry.ensureLoaded(targetEcosystem); const engine = this.getEngineForEcosystem(targetEcosystem, cwd); const { command, args } = engine.resolveUpdateArgs(); const routedArgs = this.registryRouter.injectCliFlags(targetEcosystem, args, cwd); @@ -302,6 +311,12 @@ export class PolyDispatcher { * Inspects which CLI tool powers an ecosystem */ which(ecosystem: Ecosystem, cwd?: string): { engine: string; effectiveCli: string } { + if (!engineRegistry.isAdapterLoaded(ecosystem)) { + const meta = engineRegistry.getAdapter(ecosystem); + if (meta) { + return { engine: meta.id, effectiveCli: meta.defaultCli }; + } + } const engine = this.getEngineForEcosystem(ecosystem, cwd ?? process.cwd()); return { engine: engine.name, effectiveCli: engine.getEffectiveCli() }; } diff --git a/src/doctor/checker.ts b/src/doctor/checker.ts index 31823a2..3956abe 100644 --- a/src/doctor/checker.ts +++ b/src/doctor/checker.ts @@ -361,6 +361,41 @@ export class PolyDoctor { args: ["version"], hint: "https://github.com/Carthage/Carthage", }, + { + id: "toolchain-cabal", + name: "Haskell Cabal", + cmd: "cabal", + args: ["--version"], + hint: "https://www.haskell.org/ghcup/", + }, + { + id: "toolchain-stack", + name: "Haskell Stack", + cmd: "stack", + args: ["--version"], + hint: "https://docs.haskellstack.org", + }, + { + id: "toolchain-rscript", + name: "R / Rscript", + cmd: "Rscript", + args: ["--version"], + hint: "https://cran.r-project.org", + }, + { + id: "toolchain-cpanm", + name: "Perl cpanm", + cmd: "cpanm", + args: ["--version"], + hint: "https://cpanmin.us", + }, + { + id: "toolchain-luarocks", + name: "LuaRocks", + cmd: "luarocks", + args: ["--version"], + hint: "https://luarocks.org", + }, ]; for (const tc of toolchains) { diff --git a/src/engines/core.ts b/src/engines/core.ts new file mode 100644 index 0000000..54d8e7b --- /dev/null +++ b/src/engines/core.ts @@ -0,0 +1,193 @@ +import type { EngineAdapter } from "./declarative.js"; +import { GoEngine } from "./go.js"; +import { NodeEngine } from "./node.js"; +import { PythonEngine } from "./python.js"; +import { RustEngine } from "./rust.js"; + +export 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] }; + }, +}; + +export 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] }; + }, +}; + +export 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; + }, +}; + +export 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], + }; + }, +}; + +export const cargoAdapter: EngineAdapter = { + id: "rust", + ecosystem: "cargo", + aliases: ["rust"], + purlTypes: ["cargo"], + manifests: ["Cargo.toml"], + lockfiles: ["Cargo.lock"], + osvEcosystem: "crates.io", + sbomPurlType: "cargo", + defaultCli: "rust", + 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; + }, +}; + +export 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] }; + }, +}; + +export const CORE_ADAPTERS: readonly EngineAdapter[] = [ + npmAdapter, + jsrAdapter, + pypiAdapter, + condaAdapter, + cargoAdapter, + goAdapter, +]; diff --git a/src/engines/custom.ts b/src/engines/custom.ts new file mode 100644 index 0000000..3b205d5 --- /dev/null +++ b/src/engines/custom.ts @@ -0,0 +1,222 @@ +import fs from "node:fs"; +import path from "node:path"; +import type { CustomEngineDefinition, PackageSpec, WorkspaceConfig } from "../types.js"; +import { type EngineAdapter, defineDeclarativeAdapter } from "./declarative.js"; +import { engineRegistry } from "./registry.js"; + +const LOADED_CONFIG_TIMESTAMPS = new Map(); + +function tokenizeTemplateString(template: string): string[] { + const tokens: string[] = []; + const regex = /"([^"]*)"|'([^']*)'|(\S+)/g; + for (const m of template.matchAll(regex)) { + const token = m[1] ?? m[2] ?? m[3]; + if (token !== undefined) tokens.push(token); + } + return tokens; +} + +/** + * Expands a declarative command template string or argv array against an optional PackageSpec. + * Placeholders: {name}, {namespace}, {fullName}, {version}, {cleanVersion}, {raw}. + */ +export function expandCommandTemplate( + template: string | string[] | undefined, + fallbackArgs: string[], + pkg?: PackageSpec, +): string[] { + if (!template) return fallbackArgs; + + const rawTokens = Array.isArray(template) ? [...template] : tokenizeTemplateString(template); + const fullName = pkg ? (pkg.namespace ? `${pkg.namespace}/${pkg.name}` : pkg.name) : ""; + const cleanVer = pkg?.version?.replace(/^[~^>=<\s]+/, "").trim() ?? ""; + const rawVer = pkg?.version?.trim() ?? ""; + + const expanded: string[] = []; + for (const tok of rawTokens) { + const hadPlaceholder = /\{(?:version|cleanVersion|namespace)\}/.test(tok); + let out = tok + .replace(/\{fullName\}/g, fullName) + .replace(/\{namespace\}/g, pkg?.namespace ?? "") + .replace(/\{name\}/g, pkg?.name ?? "") + .replace(/\{cleanVersion\}/g, cleanVer) + .replace(/\{version\}/g, rawVer) + .replace(/\{raw\}/g, pkg?.raw ?? ""); + + // Clean dangling version separator like "foo@" when version is unset + if (hadPlaceholder && !rawVer) { + out = out.replace(/[@=:]$/, ""); + } + if (out.length > 0) { + expanded.push(out); + } + } + return expanded; +} + +/** + * Builds an EngineAdapter from a `[engines.custom.]` entry in poly.toml. + */ +export function createCustomEngineAdapter( + name: string, + def: CustomEngineDefinition, +): EngineAdapter { + const ecosystem = name.trim().toLowerCase(); + const cmd = def.command?.trim() || ecosystem; + + return defineDeclarativeAdapter({ + id: `custom-${ecosystem}`, + ecosystem, + aliases: def.aliases ?? [], + purlTypes: def.purlType ? [def.purlType] : [ecosystem], + manifests: def.manifests, + lockfiles: def.lockfiles ?? [], + osvEcosystem: def.osvEcosystem || undefined, + sbomPurlType: def.sbomPurlType ?? def.purlType ?? ecosystem, + supportedClis: [cmd], + commands: { + command: cmd, + add: (pkg) => expandCommandTemplate(def.add, ["add", pkg.name], pkg), + remove: (pkg) => expandCommandTemplate(def.remove, ["remove", pkg.name], pkg), + install: () => expandCommandTemplate(def.install, ["install"]), + update: (pkg) => + expandCommandTemplate(def.update, pkg ? ["update", pkg.name] : ["update"], pkg), + }, + resolveScriptCommand: (script) => { + if (script === "test" && def.test) { + return [cmd, expandCommandTemplate(def.test, ["test"])]; + } + if (def.script) { + return [ + cmd, + expandCommandTemplate(def.script, [script]).map((s) => s.replace(/\{script\}/g, script)), + ]; + } + return [cmd, [script]]; + }, + }); +} + +/** + * Registers custom engines from a parsed WorkspaceConfig into EngineRegistry. + */ +export function registerCustomEnginesFromConfig(config?: WorkspaceConfig): EngineAdapter[] { + const custom = config?.engines?.custom; + if (!custom) return []; + + const registered: EngineAdapter[] = []; + for (const [name, def] of Object.entries(custom)) { + if (!def.manifests || def.manifests.length === 0) continue; + const adapter = createCustomEngineAdapter(name, def); + engineRegistry.register(adapter); + registered.push(adapter); + } + return registered; +} + +/** + * Lightweight parser for [engines.custom.*] blocks inside a directory's poly.toml/poly.json + * so detector lookups discover custom manifests without creating circular dependencies with config.ts. + */ +export function syncCustomEnginesInDir(dir: string): EngineAdapter[] { + const jsonPath = path.join(dir, "poly.json"); + const tomlPath = path.join(dir, "poly.toml"); + + const activeFile = fs.existsSync(tomlPath) ? tomlPath : fs.existsSync(jsonPath) ? jsonPath : null; + if (!activeFile) return []; + + const mtimeMs = fs.statSync(activeFile).mtimeMs; + if (LOADED_CONFIG_TIMESTAMPS.get(activeFile) === mtimeMs) { + return []; + } + LOADED_CONFIG_TIMESTAMPS.set(activeFile, mtimeMs); + + try { + if (activeFile.endsWith(".json")) { + const parsed = JSON.parse(fs.readFileSync(activeFile, "utf-8")) as WorkspaceConfig; + return registerCustomEnginesFromConfig(parsed); + } + + const content = fs.readFileSync(activeFile, "utf-8"); + const customMap = parseCustomEnginesFromToml(content); + return registerCustomEnginesFromConfig({ + name: "workspace", + members: [], + engines: { custom: customMap }, + }); + } catch { + return []; + } +} + +export function parseCustomEnginesFromToml( + content: string, +): Record { + const custom: Record = {}; + let activeName: string | null = null; + + for (const rawLine of content.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith("#")) continue; + + if (line.startsWith("[") && line.endsWith("]")) { + const section = line.slice(1, -1).trim(); + const match = section.match(/^engines\.custom\.([a-z0-9_-]+)$/i); + if (match?.[1]) { + activeName = match[1].toLowerCase(); + custom[activeName] ??= { + name: activeName, + manifests: [], + lockfiles: [], + command: activeName, + }; + } else { + activeName = null; + } + continue; + } + + if (!activeName) continue; + const eqIdx = line.indexOf("="); + if (eqIdx === -1) continue; + + const key = line.slice(0, eqIdx).trim(); + const rawVal = line.slice(eqIdx + 1).trim(); + const def = custom[activeName]; + + const parseArrayOrString = (v: string): string[] => { + if (v.startsWith("[") && v.endsWith("]")) { + return (v.match(/["']([^"']+)["']/g) ?? []).map((s) => s.slice(1, -1)); + } + return [v.replace(/^["']|["']$/g, "")]; + }; + const cleanStr = (v: string): string => v.replace(/^["']|["']$/g, ""); + + if (key === "manifest" || key === "manifests") { + def.manifests.push(...parseArrayOrString(rawVal)); + } else if (key === "lockfile" || key === "lockfiles") { + def.lockfiles = [...(def.lockfiles ?? []), ...parseArrayOrString(rawVal)]; + } else if (key === "aliases") { + def.aliases = parseArrayOrString(rawVal); + } else if (key === "command") { + def.command = cleanStr(rawVal); + } else if (key === "purl_type" || key === "purlType") { + def.purlType = cleanStr(rawVal); + } else if (key === "osv_ecosystem" || key === "osvEcosystem") { + def.osvEcosystem = cleanStr(rawVal) || undefined; + } else if (key === "sbom_purl_type" || key === "sbomPurlType") { + def.sbomPurlType = cleanStr(rawVal); + } else if ( + key === "add" || + key === "remove" || + key === "install" || + key === "update" || + key === "test" || + key === "script" + ) { + def[key] = rawVal.startsWith("[") ? parseArrayOrString(rawVal) : cleanStr(rawVal); + } + } + + return custom; +} diff --git a/src/engines/index.ts b/src/engines/index.ts index 053d756..f9c3102 100644 --- a/src/engines/index.ts +++ b/src/engines/index.ts @@ -1,3 +1,31 @@ +import { BACKEND_MOBILE_ADAPTERS } from "./backend-mobile.js"; +import { CORE_ADAPTERS } from "./core.js"; +import { CPP_JULIA_ADAPTERS } from "./cpp-julia.js"; +import { LONGTAIL_ADAPTERS } from "./longtail.js"; +import { engineRegistry } from "./registry.js"; +import { TIER2_MANIFEST_ADAPTERS } from "./tier2-manifest.js"; + +// Side-effect registration when importing the full barrel (`engines/index.js`) so synchronous callers work seamlessly. +for (const adapter of [ + ...CORE_ADAPTERS, + ...BACKEND_MOBILE_ADAPTERS, + ...CPP_JULIA_ADAPTERS, + ...TIER2_MANIFEST_ADAPTERS, + ...LONGTAIL_ADAPTERS, +]) { + engineRegistry.register(adapter); +} + +export { + CORE_ADAPTERS, + cargoAdapter, + condaAdapter, + goAdapter, + jsrAdapter, + npmAdapter, + pypiAdapter, +} from "./core.js"; + export { BaseEngine } from "./base.js"; export { BACKEND_MOBILE_ADAPTERS, @@ -14,16 +42,12 @@ export { vcpkgAdapter, } from "./cpp-julia.js"; export { - TIER2_MANIFEST_ADAPTERS, - carthageAdapter, - cocoapodsAdapter, - gradleAdapter, - hexAdapter, - mavenAdapter, - rebar3Adapter, - sbtAdapter, - swiftAdapter, -} from "./tier2-manifest.js"; + createCustomEngineAdapter, + expandCommandTemplate, + parseCustomEnginesFromToml, + registerCustomEnginesFromConfig, + syncCustomEnginesInDir, +} from "./custom.js"; export { DeclarativeEngine, defineDeclarativeAdapter, @@ -31,6 +55,13 @@ export { type EngineAdapter, } from "./declarative.js"; export { GoEngine } from "./go.js"; +export { + LONGTAIL_ADAPTERS, + cpanAdapter, + cranAdapter, + hackageAdapter, + luarocksAdapter, +} from "./longtail.js"; export { NodeEngine, type NodeCli } from "./node.js"; export { PythonEngine, type PythonCli } from "./python.js"; export { @@ -39,3 +70,14 @@ export { resolveEcosystemLockContext, } from "./registry.js"; export { RustEngine } from "./rust.js"; +export { + TIER2_MANIFEST_ADAPTERS, + carthageAdapter, + cocoapodsAdapter, + gradleAdapter, + hexAdapter, + mavenAdapter, + rebar3Adapter, + sbtAdapter, + swiftAdapter, +} from "./tier2-manifest.js"; diff --git a/src/engines/longtail.ts b/src/engines/longtail.ts new file mode 100644 index 0000000..3f721d1 --- /dev/null +++ b/src/engines/longtail.ts @@ -0,0 +1,148 @@ +import fs from "node:fs"; +import path from "node:path"; +import type { EngineContext, PackageSpec } from "../types.js"; +import { type EngineAdapter, defineDeclarativeAdapter } from "./declarative.js"; + +function cleanVer(version?: string): string | undefined { + return version?.replace(/^[~^>=<\s]+/, "").trim() || undefined; +} + +function isStackProject(ctx?: EngineContext): boolean { + if (ctx?.preferredCli === "stack") return true; + if (ctx?.lockfile === "stack.yaml.lock") return true; + if (ctx?.cwd && fs.existsSync(path.join(ctx.cwd, "stack.yaml"))) return true; + return false; +} + +/** Haskell — Hackage (Cabal & Stack) */ +export const hackageAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "hackage", + ecosystem: "hackage", + aliases: ["haskell", "cabal", "stack"], + purlTypes: ["hackage"], + manifests: ["*.cabal", "package.yaml"], + lockfiles: ["cabal.project.freeze", "stack.yaml.lock"], + osvEcosystem: "Hackage", + sbomPurlType: "hackage", + supportedClis: ["cabal", "stack"], + commands: { + command: (ctx) => (isStackProject(ctx) ? "stack" : "cabal"), + add: (pkg, ctx) => { + const ver = cleanVer(pkg.version); + if (isStackProject(ctx)) { + return ["install", ver ? `${pkg.name}-${ver}` : pkg.name]; + } + const args = ["install", pkg.name, "--lib"]; + if (ver) args.push(`--constraint=${pkg.name} ==${ver}`); + return args; + }, + remove: (_pkg, ctx) => (isStackProject(ctx) ? ["clean"] : ["clean"]), + install: (ctx) => + isStackProject(ctx) ? ["build", "--only-dependencies"] : ["build", "--only-dependencies"], + update: () => ["update"], + }, + resolveScriptCommand: (script, ctx) => { + const cli = isStackProject(ctx) ? "stack" : "cabal"; + return script === "test" ? [cli, ["test"]] : [cli, [script]]; + }, +}); + +/** R — CRAN / Pak / renv */ +export const cranAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "cran", + ecosystem: "cran", + aliases: ["r", "pak", "renv"], + purlTypes: ["cran"], + manifests: ["DESCRIPTION", "renv.lock"], + lockfiles: ["renv.lock"], + osvEcosystem: "CRAN", + sbomPurlType: "cran", + supportedClis: ["Rscript"], + commands: { + command: "Rscript", + add: (pkg) => { + const ver = cleanVer(pkg.version); + const spec = ver ? `${pkg.name}@${ver}` : pkg.name; + return ["-e", `pak::pkg_install('${spec}'); renv::snapshot(prompt = FALSE)`]; + }, + remove: (pkg) => ["-e", `remove.packages('${pkg.name}')`], + install: () => [ + "-e", + "if (file.exists('renv.lock')) renv::restore(prompt = FALSE) else pak::local_install_deps()", + ], + update: (pkg) => [ + "-e", + pkg + ? `pak::pkg_install('${pkg.name}', upgrade = TRUE); renv::snapshot(prompt = FALSE)` + : "renv::update(prompt = FALSE); renv::snapshot(prompt = FALSE)", + ], + }, + resolveScriptCommand: (script) => + script === "test" ? ["Rscript", ["-e", "testthat::test_local()"]] : ["Rscript", [script]], + injectRegistryEnv: (endpoint, env) => { + env.RENV_CONFIG_REPOS_OVERRIDE = endpoint.url; + }, +}); + +/** Perl — CPAN / cpanm / PPM */ +export const cpanAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "cpan", + ecosystem: "cpan", + aliases: ["perl", "cpanm", "ppm"], + purlTypes: ["cpan"], + manifests: ["cpanfile", "Makefile.PL"], + lockfiles: ["cpanfile.snapshot"], + osvEcosystem: undefined, + sbomPurlType: "cpan", + supportedClis: ["cpanm", "cpan", "ppm"], + commands: { + command: (ctx) => ctx?.preferredCli ?? "cpanm", + add: (pkg, ctx) => { + const cli = ctx?.preferredCli ?? "cpanm"; + if (cli === "ppm") return ["install", pkg.name]; + const ver = cleanVer(pkg.version); + return [ver ? `${pkg.name}@${ver}` : pkg.name]; + }, + remove: (pkg, ctx) => (ctx?.preferredCli === "ppm" ? ["remove", pkg.name] : ["-U", pkg.name]), + install: (ctx) => + ctx?.preferredCli === "cpan" ? [".", "--installdeps"] : ["--installdeps", "."], + update: (pkg) => (pkg ? [pkg.name] : ["--installdeps", "."]), + }, + resolveScriptCommand: (script) => + script === "test" ? ["prove", ["-r", "t"]] : ["perl", [script]], +}); + +/** Lua — LuaRocks */ +export const luarocksAdapter: EngineAdapter = defineDeclarativeAdapter({ + id: "luarocks", + ecosystem: "luarocks", + aliases: ["lua"], + purlTypes: ["luarocks"], + manifests: ["*.rockspec"], + lockfiles: [], + osvEcosystem: undefined, + sbomPurlType: "luarocks", + supportedClis: ["luarocks"], + commands: { + command: "luarocks", + add: (pkg) => { + const ver = cleanVer(pkg.version); + return ["install", pkg.name, ...(ver ? [ver] : [])]; + }, + remove: (pkg) => ["remove", pkg.name], + install: () => ["install", "--only-deps"], + update: (pkg) => (pkg ? ["install", pkg.name] : ["install", "--only-deps"]), + }, + resolveScriptCommand: (script) => + script === "test" ? ["luarocks", ["test"]] : ["lua", [script]], + injectRegistryEnv: (endpoint, env) => { + env.LUAROCKS_SERVER = endpoint.url; + }, +}); + +export const LONGTAIL_ADAPTERS: readonly EngineAdapter[] = [ + hackageAdapter, + cranAdapter, + cpanAdapter, + luarocksAdapter, +]; diff --git a/src/engines/registry.ts b/src/engines/registry.ts index ee0d0a8..8d21edf 100644 --- a/src/engines/registry.ts +++ b/src/engines/registry.ts @@ -1,27 +1,87 @@ import fs from "node:fs"; +import path from "node:path"; import type { Ecosystem, EngineContext } from "../types.js"; -import { BACKEND_MOBILE_ADAPTERS } from "./backend-mobile.js"; import type { BaseEngine } from "./base.js"; -import { CPP_JULIA_ADAPTERS } from "./cpp-julia.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"; -import { TIER2_MANIFEST_ADAPTERS } from "./tier2-manifest.js"; +import type { EngineAdapter } from "./declarative.js"; + +export type EngineGroupLoader = () => Promise; + +/** + * Lightweight descriptor registered at startup without loading heavy engine or mutator modules. + */ +function createDescriptorStub( + meta: Omit, + groupKey: string, + loader: EngineGroupLoader, + registry: EngineRegistry, +): EngineAdapter { + return { + ...meta, + createEngine: () => { + throw new Error( + `Adapter '${meta.ecosystem}' is lazy-loaded (${groupKey}). Call 'await engineRegistry.ensureLoaded("${meta.ecosystem}")' first or import via 'engines/index.js'.`, + ); + }, + __lazyGroup: groupKey, + __loader: loader, + __registry: registry, + } as EngineAdapter & { + __lazyGroup?: string; + __loader?: EngineGroupLoader; + __registry?: EngineRegistry; + }; +} + +interface LazyEntry { + groupKey: string; + loader: EngineGroupLoader; +} /** * Central extensible EngineAdapter registry powering detection, PURL parsing, - * native command dispatch, OSV compliance mapping, and private registry injection. + * native command dispatch, OSV compliance mapping, private registry injection, + * and on-demand lazy loading of ecosystem engines. */ export class EngineRegistry { private adapters = new Map(); private aliasIndex = new Map(); private purlIndex = new Map(); + private lazyLoaders = new Map(); + private loadedAdapters = new Set(); + private loadedGroups = new Map>(); + /** + * Registers an eager or fully hydrated EngineAdapter and marks it loaded. + */ register(adapter: EngineAdapter): void { const key = adapter.ecosystem.toLowerCase(); this.adapters.set(key, adapter); + this.loadedAdapters.add(key); + this.lazyLoaders.delete(key); + this.indexMetadata(adapter); + } + + /** + * Registers a lightweight adapter descriptor with an async module loader. + * Only metadata (manifests, lockfiles, aliases, OSV/SBOM mappings) is held at startup; + * actual engine/mutator code is dynamically imported when first activated. + */ + registerLazy( + meta: Omit, + groupKey: string, + loader: EngineGroupLoader, + ): void { + const key = meta.ecosystem.toLowerCase(); + if (this.loadedAdapters.has(key)) return; + + const stub = createDescriptorStub(meta, groupKey, loader, this); + this.adapters.set(key, stub); + this.lazyLoaders.set(key, { groupKey, loader }); + this.indexMetadata(stub); + } + + private indexMetadata(adapter: EngineAdapter): void { + const key = adapter.ecosystem.toLowerCase(); this.aliasIndex.set(key, adapter.ecosystem); this.purlIndex.set(key, adapter.ecosystem); @@ -39,6 +99,8 @@ export class EngineRegistry { if (!existing) return false; this.adapters.delete(key); + this.loadedAdapters.delete(key); + this.lazyLoaders.delete(key); this.aliasIndex.delete(key); this.purlIndex.delete(key); @@ -81,6 +143,87 @@ export class EngineRegistry { return this.getAdapter(ecosystemOrAlias) !== undefined; } + isAdapterLoaded(ecosystemOrAlias: string): boolean { + const resolved = this.resolveEcosystem(ecosystemOrAlias); + return resolved ? this.loadedAdapters.has(resolved.toLowerCase()) : false; + } + + getLoadedEcosystems(): Ecosystem[] { + return Array.from(this.loadedAdapters); + } + + /** + * Lazily imports and registers the implementation module for a single ecosystem on demand. + */ + async ensureLoaded(ecosystemOrAlias: string): Promise { + const resolved = this.resolveEcosystem(ecosystemOrAlias); + if (!resolved) { + throw new Error( + `Unsupported ecosystem '${ecosystemOrAlias}'. Registered ecosystems: ${this.listEcosystems().join(", ")}`, + ); + } + + const key = resolved.toLowerCase(); + const lazy = this.lazyLoaders.get(key); + if (lazy) { + let groupPromise = this.loadedGroups.get(lazy.groupKey); + if (!groupPromise) { + groupPromise = lazy.loader(); + this.loadedGroups.set(lazy.groupKey, groupPromise); + } + const loaded = await groupPromise; + for (const adapter of loaded) { + this.register(adapter); + } + } + + const active = this.adapters.get(key); + if (!active) { + throw new Error(`Failed to activate engine adapter for '${ecosystemOrAlias}'.`); + } + return active; + } + + /** + * Preloads ONLY the adapters corresponding to manifests actually present in `dir` (and parent git root). + */ + async loadForDirectory(dir: string): Promise { + const activated: Ecosystem[] = []; + const targetDir = path.resolve(dir); + + for (const adapter of this.getAdapters()) { + let found = false; + for (const pattern of adapter.manifests) { + if (!pattern.includes("*") && !pattern.includes("?")) { + if (fs.existsSync(path.join(targetDir, pattern))) { + found = true; + break; + } + } else { + try { + const entries = fs.readdirSync(targetDir); + const escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + if (entries.some((e) => new RegExp(`^${escaped}$`, "i").test(e))) { + found = true; + break; + } + } catch { + // ignore unreadable dir + } + } + } + if (found) { + await this.ensureLoaded(adapter.ecosystem); + activated.push(adapter.ecosystem); + } + } + + return activated; + } + createEngine(ecosystemOrAlias: string, ctx?: EngineContext): BaseEngine { const adapter = this.getAdapter(ecosystemOrAlias); if (!adapter) { @@ -88,6 +231,7 @@ export class EngineRegistry { `Unsupported ecosystem '${ecosystemOrAlias}'. Registered ecosystems: ${this.listEcosystems().join(", ")}`, ); } + this.loadedAdapters.add(adapter.ecosystem.toLowerCase()); return adapter.createEngine({ ...ctx, ecosystem: adapter.ecosystem }); } @@ -103,200 +247,529 @@ export class EngineRegistry { 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; +const loadCoreGroup: EngineGroupLoader = async () => + Array.from((await import("./core.js")).CORE_ADAPTERS); + +const loadBackendMobileGroup: EngineGroupLoader = async () => + Array.from((await import("./backend-mobile.js")).BACKEND_MOBILE_ADAPTERS); + +const loadCppJuliaGroup: EngineGroupLoader = async () => + Array.from((await import("./cpp-julia.js")).CPP_JULIA_ADAPTERS); + +const loadTier2ManifestGroup: EngineGroupLoader = async () => + Array.from((await import("./tier2-manifest.js")).TIER2_MANIFEST_ADAPTERS); + +const loadLongtailGroup: EngineGroupLoader = async () => + Array.from((await import("./longtail.js")).LONGTAIL_ADAPTERS); + +// Lightweight descriptors registered immediately (0 heavy module imports at CLI startup) +const LAZY_DESCRIPTORS: Array<{ + meta: Omit; + groupKey: string; + loader: EngineGroupLoader; +}> = [ + // Core (Group: core) + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + 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"], + resolveScriptCommand: (script) => ["npm", ["run", script]], + injectRegistryEnv: (e, env) => { + env.NPM_CONFIG_REGISTRY = e.url; + env.npm_config_registry = e.url; + if (e.caFile) env.NPM_CONFIG_CAFILE = e.caFile; + }, + injectRegistryFlags: (e, args) => { + if (!args.includes("--registry")) args.push("--registry", e.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] }; + }, + }, }, - injectRegistryFlags: (endpoint, args) => { - if (!args.includes("--registry")) { - args.push("--registry", endpoint.url); - } + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + 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"], + 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] }; + }, + }, }, - injectSandboxFlags: (_command, args) => { - const modified = [...args]; - if (!modified.includes("--ignore-scripts")) { - modified.push("--ignore-scripts"); - } - return modified; + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + 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"], + resolveScriptCommand: (script) => ["python", ["-m", script]], + injectRegistryEnv: (e, env) => { + env.UV_INDEX_URL = e.url; + env.PIP_INDEX_URL = e.url; + if (e.trustedHost) env.PIP_TRUSTED_HOST = e.trustedHost; + }, + injectRegistryFlags: (e, args) => { + if (!args.includes("--index-url")) args.push("--index-url", e.url); + }, + injectSandboxFlags: (command, args) => { + if (command === "pip" && !args.includes("--no-build-isolation")) { + return [...args, "--no-build-isolation"]; + } + 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("bun")) { - return { command: "bunx", args: [fullPkg, ...trailingArgs] }; - } - return { command: "npx", args: ["--yes", fullPkg, ...trailingArgs] }; + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + 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"], + resolveScriptCommand: (script) => [ + "conda", + ["run", "--no-capture-output", "python", "-m", script], + ], + injectRegistryEnv: (e, env) => { + env.CONDA_CHANNELS = e.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 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; + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + id: "rust", + ecosystem: "cargo", + aliases: ["rust"], + purlTypes: ["cargo"], + manifests: ["Cargo.toml"], + lockfiles: ["Cargo.lock"], + osvEcosystem: "crates.io", + sbomPurlType: "cargo", + defaultCli: "rust", + supportedClis: ["cargo"], + resolveScriptCommand: (script) => { + if (script === "dev" || script === "start") return ["cargo", ["run"]]; + if (script === "test") return ["cargo", ["test"]]; + return ["cargo", [script]]; + }, + injectRegistryEnv: (e, env) => { + env.CARGO_REGISTRIES_CRATES_IO_INDEX = e.url; + }, + }, }, - 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] }; + { + groupKey: "core", + loader: loadCoreGroup, + meta: { + id: "go", + ecosystem: "go", + aliases: ["golang"], + purlTypes: ["golang", "go"], + manifests: ["go.mod"], + lockfiles: ["go.sum"], + osvEcosystem: "Go", + sbomPurlType: "golang", + defaultCli: "go", + supportedClis: ["go"], + resolveScriptCommand: (script) => { + if (script === "dev" || script === "start") return ["go", ["run", "."]]; + if (script === "test") return ["go", ["test", "./..."]]; + return ["go", [script]]; + }, + injectRegistryEnv: (e, env) => { + env.GOPROXY = e.url; + }, + resolveEphemeralCommand: (spec, trailingArgs) => { + const target = spec.version ? `${spec.name}@${spec.version}` : `${spec.name}@latest`; + return { command: "go", args: ["run", target, ...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; + // Phase 2 Backend & Mobile + { + groupKey: "backend-mobile", + loader: loadBackendMobileGroup, + meta: { + id: "dotnet", + ecosystem: "nuget", + aliases: ["dotnet", "csharp", "paket"], + purlTypes: ["nuget"], + manifests: ["*.csproj", "*.fsproj", "*.vbproj", "paket.dependencies"], + lockfiles: ["packages.lock.json", "paket.lock"], + osvEcosystem: "NuGet", + sbomPurlType: "nuget", + defaultCli: "dotnet", + supportedClis: ["dotnet", "paket"], + }, }, - injectRegistryFlags: (endpoint, args) => { - if (!args.includes("--index-url")) { - args.push("--index-url", endpoint.url); - } + { + groupKey: "backend-mobile", + loader: loadBackendMobileGroup, + meta: { + id: "composer", + ecosystem: "composer", + aliases: ["php", "packagist", "pear"], + purlTypes: ["composer"], + manifests: ["composer.json", "package.xml"], + lockfiles: ["composer.lock"], + osvEcosystem: "Packagist", + sbomPurlType: "composer", + defaultCli: "composer", + supportedClis: ["composer", "pear"], + }, }, - injectSandboxFlags: (command, args) => { - if (command === "pip" && !args.includes("--no-build-isolation")) { - return [...args, "--no-build-isolation"]; - } - return args; + { + groupKey: "backend-mobile", + loader: loadBackendMobileGroup, + meta: { + id: "bundler", + ecosystem: "gem", + aliases: ["ruby", "bundler", "rubygems"], + purlTypes: ["gem"], + manifests: ["Gemfile", "*.gemspec"], + lockfiles: ["Gemfile.lock"], + osvEcosystem: "RubyGems", + sbomPurlType: "gem", + defaultCli: "bundle", + supportedClis: ["bundle", "gem"], + }, }, -}; - -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; + { + groupKey: "backend-mobile", + loader: loadBackendMobileGroup, + meta: { + id: "pub", + ecosystem: "pub", + aliases: ["dart", "flutter"], + purlTypes: ["pub"], + manifests: ["pubspec.yaml"], + lockfiles: ["pubspec.lock"], + osvEcosystem: "Pub", + sbomPurlType: "pub", + defaultCli: "dart", + supportedClis: ["dart", "flutter"], + }, }, - 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], - }; + // Phase 3 C/C++ & Julia + { + groupKey: "cpp-julia", + loader: loadCppJuliaGroup, + meta: { + id: "conan", + ecosystem: "conan", + aliases: ["cpp", "c++"], + purlTypes: ["conan"], + manifests: ["conanfile.txt", "conanfile.py"], + lockfiles: ["conan.lock"], + osvEcosystem: "ConanCenter", + sbomPurlType: "conan", + defaultCli: "conan", + supportedClis: ["conan"], + }, }, -}; - -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]]; + { + groupKey: "cpp-julia", + loader: loadCppJuliaGroup, + meta: { + id: "vcpkg", + ecosystem: "vcpkg", + aliases: [], + purlTypes: ["vcpkg"], + manifests: ["vcpkg.json", "vcpkg-configuration.json"], + lockfiles: ["vcpkg-configuration.json"], + sbomPurlType: "vcpkg", + defaultCli: "vcpkg", + supportedClis: ["vcpkg"], + }, }, - injectRegistryEnv: (endpoint, env) => { - env.CARGO_REGISTRIES_CRATES_IO_INDEX = endpoint.url; + { + groupKey: "cpp-julia", + loader: loadCppJuliaGroup, + meta: { + id: "meson", + ecosystem: "meson", + aliases: ["wrap", "wrapdb"], + purlTypes: ["meson", "wrap"], + manifests: ["meson.build"], + lockfiles: [], + sbomPurlType: "meson", + defaultCli: "meson", + supportedClis: ["meson"], + }, }, -}; - -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]]; + { + groupKey: "cpp-julia", + loader: loadCppJuliaGroup, + meta: { + id: "julia", + ecosystem: "julia", + aliases: ["pkg.jl", "pkgjl"], + purlTypes: ["julia"], + manifests: ["Project.toml"], + lockfiles: ["Manifest.toml"], + sbomPurlType: "julia", + defaultCli: "julia", + supportedClis: ["julia"], + }, }, - injectRegistryEnv: (endpoint, env) => { - env.GOPROXY = endpoint.url; + // Phase 4 Tier 2 Manifest-Rewriting + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "maven", + ecosystem: "maven", + aliases: ["mvn", "java", "jvm", "ivy"], + purlTypes: ["maven"], + manifests: ["pom.xml", "ivy.xml"], + lockfiles: [], + osvEcosystem: "Maven", + sbomPurlType: "maven", + defaultCli: "mvn", + supportedClis: ["mvn", "ant"], + }, }, - resolveEphemeralCommand: (spec, trailingArgs) => { - const target = spec.version ? `${spec.name}@${spec.version}` : `${spec.name}@latest`; - return { command: "go", args: ["run", target, ...trailingArgs] }; + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + 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", + defaultCli: "gradle", + supportedClis: ["gradle"], + }, }, -}; - -engineRegistry.register(npmAdapter); -engineRegistry.register(jsrAdapter); -engineRegistry.register(pypiAdapter); -engineRegistry.register(condaAdapter); -engineRegistry.register(cargoAdapter); -engineRegistry.register(goAdapter); -for (const adapter of BACKEND_MOBILE_ADAPTERS) { - engineRegistry.register(adapter); -} -for (const adapter of CPP_JULIA_ADAPTERS) { - engineRegistry.register(adapter); -} -for (const adapter of TIER2_MANIFEST_ADAPTERS) { - engineRegistry.register(adapter); + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "sbt", + ecosystem: "sbt", + aliases: ["scala"], + purlTypes: ["sbt"], + manifests: ["build.sbt"], + lockfiles: [], + osvEcosystem: "Maven", + sbomPurlType: "maven", + defaultCli: "sbt", + supportedClis: ["sbt"], + }, + }, + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "mix", + ecosystem: "hex", + aliases: ["elixir", "mix"], + purlTypes: ["hex"], + manifests: ["mix.exs"], + lockfiles: ["mix.lock"], + osvEcosystem: "Hex", + sbomPurlType: "hex", + defaultCli: "mix", + supportedClis: ["mix"], + }, + }, + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "rebar3", + ecosystem: "rebar3", + aliases: ["erlang", "rebar"], + purlTypes: ["rebar3"], + manifests: ["rebar.config"], + lockfiles: ["rebar.lock"], + osvEcosystem: "Hex", + sbomPurlType: "hex", + defaultCli: "rebar3", + supportedClis: ["rebar3"], + }, + }, + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "swift", + ecosystem: "swift", + aliases: ["spm", "swiftpm"], + purlTypes: ["swift"], + manifests: ["Package.swift"], + lockfiles: ["Package.resolved"], + osvEcosystem: "SwiftURL", + sbomPurlType: "swift", + defaultCli: "swift", + supportedClis: ["swift"], + }, + }, + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "cocoapods", + ecosystem: "cocoapods", + aliases: ["pod", "pods"], + purlTypes: ["cocoapods"], + manifests: ["Podfile", "*.podspec"], + lockfiles: ["Podfile.lock"], + sbomPurlType: "cocoapods", + defaultCli: "pod", + supportedClis: ["pod"], + }, + }, + { + groupKey: "tier2-manifest", + loader: loadTier2ManifestGroup, + meta: { + id: "carthage", + ecosystem: "carthage", + aliases: [], + purlTypes: ["carthage"], + manifests: ["Cartfile"], + lockfiles: ["Cartfile.resolved"], + sbomPurlType: "github", + defaultCli: "carthage", + supportedClis: ["carthage"], + }, + }, + // Phase 5 Long-Tail Scripting + { + groupKey: "longtail", + loader: loadLongtailGroup, + meta: { + id: "hackage", + ecosystem: "hackage", + aliases: ["haskell", "cabal", "stack"], + purlTypes: ["hackage"], + manifests: ["*.cabal", "package.yaml"], + lockfiles: ["cabal.project.freeze", "stack.yaml.lock"], + osvEcosystem: "Hackage", + sbomPurlType: "hackage", + defaultCli: "cabal", + supportedClis: ["cabal", "stack"], + }, + }, + { + groupKey: "longtail", + loader: loadLongtailGroup, + meta: { + id: "cran", + ecosystem: "cran", + aliases: ["r", "pak", "renv"], + purlTypes: ["cran"], + manifests: ["DESCRIPTION", "renv.lock"], + lockfiles: ["renv.lock"], + osvEcosystem: "CRAN", + sbomPurlType: "cran", + defaultCli: "Rscript", + supportedClis: ["Rscript"], + }, + }, + { + groupKey: "longtail", + loader: loadLongtailGroup, + meta: { + id: "cpan", + ecosystem: "cpan", + aliases: ["perl", "cpanm", "ppm"], + purlTypes: ["cpan"], + manifests: ["cpanfile", "Makefile.PL"], + lockfiles: ["cpanfile.snapshot"], + sbomPurlType: "cpan", + defaultCli: "cpanm", + supportedClis: ["cpanm", "cpan", "ppm"], + }, + }, + { + groupKey: "longtail", + loader: loadLongtailGroup, + meta: { + id: "luarocks", + ecosystem: "luarocks", + aliases: ["lua"], + purlTypes: ["luarocks"], + manifests: ["*.rockspec"], + lockfiles: [], + sbomPurlType: "luarocks", + defaultCli: "luarocks", + supportedClis: ["luarocks"], + }, + }, +]; + +for (const item of LAZY_DESCRIPTORS) { + engineRegistry.registerLazy(item.meta, item.groupKey, item.loader); } /** Ensures a PackageSpec target cleanly detects its first existing manifest file in cwd if missing. */ @@ -322,5 +795,3 @@ export function resolveEcosystemLockContext(ecosystem: Ecosystem, cwd: string): return { cwd, ecosystem: adapter.ecosystem, manifest, lockfile }; } - -export { defineDeclarativeAdapter }; diff --git a/src/outdated/checker.ts b/src/outdated/checker.ts index b98c73a..d886918 100644 --- a/src/outdated/checker.ts +++ b/src/outdated/checker.ts @@ -4,6 +4,7 @@ import type { Ecosystem } from "../types.js"; import { resolveWorkspaceMembers } from "../workspace/config.js"; import { extractBackendMobileDependencies, + extractLongTailDependencies, extractTier2ManifestDependencies, } from "../workspace/crypto.js"; import { compareSemver } from "./semver.js"; @@ -382,6 +383,113 @@ async function fetchSwiftLatest(name: string): Promise { } } +async function fetchHackageLatest(name: string): Promise { + const cacheKey = `hackage:${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://hackage.haskell.org/package/${encodeURIComponent(name)}/preferred.json`, + { + signal: controller.signal, + headers: { Accept: "application/json" }, + }, + ); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { "normal-version"?: string[] }; + const versions = data["normal-version"] ?? []; + const latest = versions[0] ?? null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchCranLatest(name: string): Promise { + const cacheKey = `cran:${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://crandb.r-pkg.org/${encodeURIComponent(name)}`, { + signal: controller.signal, + }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { Version?: string }; + const latest = data.Version || null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchCpanLatest(name: string): Promise { + const dist = name.replace(/::/g, "-"); + const cacheKey = `cpan:${dist}`; + 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://fastapi.metacpan.org/v1/release/${encodeURIComponent(dist)}`, { + signal: controller.signal, + }); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { version?: string }; + const latest = data.version ? String(data.version).replace(/^v/, "") : null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + +async function fetchLuaRocksLatest(name: string): Promise { + const cacheKey = `luarocks:${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://luarocks.org/modules/luarocks/${encodeURIComponent(name)}.json`, + { signal: controller.signal }, + ); + clearTimeout(timer); + if (!res.ok) { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } + const data = (await res.json()) as { version?: string; versions?: Array<{ version?: string }> }; + const latest = data.version ?? data.versions?.[0]?.version ?? null; + REGISTRY_CACHE.set(cacheKey, latest); + return latest; + } catch { + REGISTRY_CACHE.set(cacheKey, null); + return null; + } +} + /** * Dispatches to registry fetcher based on ecosystem. */ @@ -418,6 +526,14 @@ export async function fetchLatestVersion( case "swift": case "carthage": return fetchSwiftLatest(name); + case "hackage": + return fetchHackageLatest(name); + case "cran": + return fetchCranLatest(name); + case "cpan": + return fetchCpanLatest(name); + case "luarocks": + return fetchLuaRocksLatest(name); default: return null; } @@ -590,6 +706,21 @@ function extractDeclaredDependencies( } break; } + case "hackage": + case "cran": + case "cpan": + case "luarocks": { + for (const item of extractLongTailDependencies(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/security/registry.ts b/src/security/registry.ts index d252a7f..70983dc 100644 --- a/src/security/registry.ts +++ b/src/security/registry.ts @@ -460,6 +460,133 @@ export async function fetchRegistryMetadata( return meta; } + if (ecosystem === "hackage") { + const res = await fetch( + `https://hackage.haskell.org/package/${encodeURIComponent(packageName)}/preferred.json`, + { signal: controller.signal, headers: { Accept: "application/json" } }, + ); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { "normal-version"?: string[] }; + const versions: Record = {}; + const list = data["normal-version"] ?? []; + for (const v of list) { + versions[v] = { version: v, license: "BSD-3-CLAUSE" }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem: "hackage", + latestVersion: list[0], + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "cran") { + const res = await fetch(`https://crandb.r-pkg.org/${encodeURIComponent(packageName)}`, { + signal: controller.signal, + headers: { Accept: "application/json" }, + }); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + Version?: string; + License?: string; + "Date/Publication"?: string; + }; + const versions: Record = {}; + if (data.Version) { + versions[data.Version] = { + version: data.Version, + publishedAt: data["Date/Publication"], + license: normalizeLicenseString(data.License), + }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem: "cran", + latestVersion: data.Version, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "cpan") { + const dist = packageName.replace(/::/g, "-"); + const res = await fetch( + `https://fastapi.metacpan.org/v1/release/${encodeURIComponent(dist)}`, + { + signal: controller.signal, + headers: { Accept: "application/json" }, + }, + ); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + version?: string; + date?: string; + license?: string[]; + }; + const ver = data.version ? String(data.version).replace(/^v/, "") : undefined; + const versions: Record = {}; + if (ver) { + versions[ver] = { + version: ver, + publishedAt: data.date, + license: normalizeLicenseString(data.license?.[0] ?? "Artistic-2.0"), + }; + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem: "cpan", + latestVersion: ver, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + + if (ecosystem === "luarocks") { + const res = await fetch( + `https://luarocks.org/modules/luarocks/${encodeURIComponent(packageName)}.json`, + { signal: controller.signal, headers: { Accept: "application/json" } }, + ); + clearTimeout(timer); + if (!res.ok) return null; + + const data = (await res.json()) as { + version?: string; + license?: string; + versions?: Array<{ version?: string; license?: string }>; + }; + const versions: Record = {}; + const license = normalizeLicenseString(data.license ?? "MIT"); + if (data.version) { + versions[data.version] = { version: data.version, license }; + } + for (const item of data.versions ?? []) { + if (item.version) { + versions[item.version] = { + version: item.version, + license: normalizeLicenseString(item.license ?? license), + }; + } + } + const meta: RegistryMetadata = { + name: packageName, + ecosystem: "luarocks", + latestVersion: data.version ?? data.versions?.[0]?.version, + versions, + }; + REGISTRY_CACHE.set(cacheKey, meta); + return meta; + } + clearTimeout(timer); return null; } catch { diff --git a/src/types.ts b/src/types.ts index 563a315..51a9860 100644 --- a/src/types.ts +++ b/src/types.ts @@ -25,9 +25,30 @@ export type BuiltinEcosystem = | "rebar3" | "swift" | "cocoapods" - | "carthage"; + | "carthage" + | "hackage" + | "cran" + | "cpan" + | "luarocks"; export type Ecosystem = BuiltinEcosystem | (string & {}); +export interface CustomEngineDefinition { + name?: string; + manifests: string[]; + lockfiles?: string[]; + aliases?: string[]; + purlType?: string; + osvEcosystem?: string; + sbomPurlType?: string; + command: string; + add?: string | string[]; + remove?: string | string[]; + install?: string | string[]; + update?: string | string[]; + test?: string | string[]; + script?: string | string[]; +} + export interface EngineContext { cwd?: string; manifest?: string; @@ -100,7 +121,8 @@ export interface WorkspaceConfig { deno?: string; conda?: string; concurrency?: number; - [key: string]: string | number | undefined; + custom?: Record; + [key: string]: string | number | Record | undefined; }; tasks?: Record; scripts?: Record; diff --git a/src/workspace/config.ts b/src/workspace/config.ts index 353f2db..716e5d2 100644 --- a/src/workspace/config.ts +++ b/src/workspace/config.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; import { detectContexts } from "../detector/tree-walker.js"; +import { parseCustomEnginesFromToml, registerCustomEnginesFromConfig } from "../engines/custom.js"; import type { ManifestContext, WorkspaceConfig } from "../types.js"; export interface ResolvedMember { @@ -19,14 +20,18 @@ export function loadWorkspaceConfig(workspaceDir: string): WorkspaceConfig | und if (fs.existsSync(jsonPath)) { try { const content = fs.readFileSync(jsonPath, "utf-8"); - return JSON.parse(content) as WorkspaceConfig; + const parsed = JSON.parse(content) as WorkspaceConfig; + registerCustomEnginesFromConfig(parsed); + return parsed; } catch { // Ignore parse failure } } if (fs.existsSync(tomlPath)) { - return parseSimplePolyToml(fs.readFileSync(tomlPath, "utf-8")); + const parsed = parseSimplePolyToml(fs.readFileSync(tomlPath, "utf-8")); + registerCustomEnginesFromConfig(parsed); + return parsed; } return undefined; @@ -122,6 +127,12 @@ export function parseSimplePolyToml(content: string): WorkspaceConfig { } } + const customEngines = parseCustomEnginesFromToml(content); + if (Object.keys(customEngines).length > 0) { + config.engines ??= {}; + config.engines.custom = customEngines; + } + return config; } diff --git a/src/workspace/crypto.ts b/src/workspace/crypto.ts index 72f31ac..eac86da 100644 --- a/src/workspace/crypto.ts +++ b/src/workspace/crypto.ts @@ -359,6 +359,15 @@ export function extractDirectDependencies(manifestPath: string, ecosystem: Ecosy } break; } + case "hackage": + case "cran": + case "cpan": + case "luarocks": { + for (const item of extractLongTailDependencies(manifestPath, content, ecosystem)) { + deps.push(`${item.ecosystem}:${item.name}@${item.version}`); + } + break; + } } return deps.sort(); @@ -650,3 +659,156 @@ function extractCppJuliaDependencies( } return results; } + +/** + * Extracts dependency name/version pairs for Phase 5 long-tail ecosystems + * (Haskell Cabal/Stack, R DESCRIPTION/renv.lock, Perl cpanfile, Lua .rockspec). + */ +export function extractLongTailDependencies( + manifestPath: string, + content: string, + ecosystem: Ecosystem, +): ParsedManifestDep[] { + const deps: ParsedManifestDep[] = []; + const fileName = path.basename(manifestPath).toLowerCase(); + + if (ecosystem === "hackage") { + if (fileName.endsWith(".cabal")) { + let inBuildDeps = false; + for (const rawLine of content.split(/\r?\n/)) { + const cleaned = rawLine.replace(/--.*$/, ""); + if (/^\s*build-depends\s*:/i.test(cleaned)) { + inBuildDeps = true; + const after = cleaned.split(":").slice(1).join(":"); + for (const part of after.split(",")) { + const m = part + .trim() + .match(/^([A-Za-z0-9-]+)(?:\s+(?:==|>=|<=|\^>=|>|<)\s*([0-9.]+))?/); + if (m?.[1] && m[1] !== "base") { + deps.push({ ecosystem: "hackage", name: m[1], version: m[2] || "latest" }); + } + } + continue; + } + if (inBuildDeps) { + if (/^\S/.test(cleaned) || /^\s*[A-Za-z0-9-]+\s*:/.test(cleaned)) { + inBuildDeps = false; + continue; + } + for (const part of cleaned.split(",")) { + const m = part + .trim() + .match(/^([A-Za-z0-9-]+)(?:\s+(?:==|>=|<=|\^>=|>|<)\s*([0-9.]+))?/); + if (m?.[1] && m[1] !== "base") { + deps.push({ ecosystem: "hackage", name: m[1], version: m[2] || "latest" }); + } + } + } + } + } else if (fileName === "package.yaml") { + let inDeps = false; + for (const rawLine of content.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + if (trimmed === "dependencies:") { + inDeps = true; + continue; + } + if (inDeps && !rawLine.startsWith(" ") && !trimmed.startsWith("-")) { + inDeps = false; + continue; + } + if (inDeps && trimmed.startsWith("-")) { + const item = trimmed.slice(1).trim(); + const m = item.match(/^([A-Za-z0-9-]+)(?:\s+(?:==|>=|<=|\^>=|>|<)\s*([0-9.]+))?/); + if (m?.[1] && m[1] !== "base") { + deps.push({ ecosystem: "hackage", name: m[1], version: m[2] || "latest" }); + } + } + } + } + return deps; + } + + if (ecosystem === "cran") { + if (fileName === "renv.lock") { + try { + const json = JSON.parse(content) as { + Packages?: Record; + }; + for (const [key, pkg] of Object.entries(json.Packages ?? {})) { + deps.push({ + ecosystem: "cran", + name: pkg.Package ?? key, + version: pkg.Version ?? "latest", + }); + } + } catch { + // Ignore malformed renv.lock + } + return deps; + } + + let inField = false; + for (const rawLine of content.split(/\r?\n/)) { + if (/^(?:Imports|Depends|Suggests)\s*:/i.test(rawLine)) { + inField = true; + const after = rawLine.split(":").slice(1).join(":"); + for (const entry of after.split(",")) { + const m = entry.trim().match(/^([A-Za-z0-9.]+)(?:\s*\((?:>=|==)\s*([^)]+)\))?/); + if (m?.[1] && m[1] !== "R") { + deps.push({ ecosystem: "cran", name: m[1], version: m[2]?.trim() || "latest" }); + } + } + continue; + } + if (inField) { + if (/^\S/.test(rawLine)) { + inField = false; + continue; + } + for (const entry of rawLine.split(",")) { + const m = entry.trim().match(/^([A-Za-z0-9.]+)(?:\s*\((?:>=|==)\s*([^)]+)\))?/); + if (m?.[1] && m[1] !== "R") { + deps.push({ ecosystem: "cran", name: m[1], version: m[2]?.trim() || "latest" }); + } + } + } + } + return deps; + } + + if (ecosystem === "cpan") { + for (const m of content.matchAll( + /\brequires\s+["']([A-Za-z0-9_:]+)["'](?:\s*,\s*["'](?:[><=~!\s]*)?([^"']+)["'])?/g, + )) { + if (m[1]) { + deps.push({ + ecosystem: "cpan", + name: m[1], + version: m[2]?.replace(/^[><=~\s]+/, "").trim() || "latest", + }); + } + } + return deps; + } + + if (ecosystem === "luarocks") { + const depBlock = content.match(/\bdependencies\s*=\s*\{([\s\S]*?)\}/); + const inner = depBlock?.[1] ?? ""; + for (const m of inner.matchAll( + /["']([A-Za-z0-9_.-]+)(?:\s*(?:>=|==|~>|<=|>|<)\s*([^"']+))?["']/g, + )) { + if (m[1] && m[1].toLowerCase() !== "lua") { + deps.push({ + ecosystem: "luarocks", + name: m[1], + version: m[2]?.trim() || "latest", + }); + } + } + return deps; + } + + return deps; +} diff --git a/src/workspace/dispatcher.ts b/src/workspace/dispatcher.ts index 7da9d06..508d1cd 100644 --- a/src/workspace/dispatcher.ts +++ b/src/workspace/dispatcher.ts @@ -1,4 +1,4 @@ -import { engineRegistry } from "../engines/index.js"; +import { engineRegistry } from "../engines/registry.js"; import { RegistryRouter } from "../registry/index.js"; import type { Ecosystem, ExecutionResult } from "../types.js"; import { loadWorkspaceConfig, resolveWorkspaceMembers } from "./config.js"; @@ -45,6 +45,7 @@ export class WorkspaceDispatcher { const member = queue.shift(); if (!member) break; const workerPromise = (async () => { + await engineRegistry.ensureLoaded(member.context.ecosystem); const engine = this.getEngine( member.context.ecosystem, member.context.manifestFile, diff --git a/tests/completion.test.ts b/tests/completion.test.ts index d6e931b..a9de92d 100644 --- a/tests/completion.test.ts +++ b/tests/completion.test.ts @@ -63,6 +63,10 @@ test("Shell Auto-Completion - Dynamic Resolution", async (t) => { "swift", "cocoapods", "carthage", + "hackage", + "cran", + "cpan", + "luarocks", ]); }); diff --git a/tests/phase5-longtail-plugins.test.ts b/tests/phase5-longtail-plugins.test.ts new file mode 100644 index 0000000..b11cb46 --- /dev/null +++ b/tests/phase5-longtail-plugins.test.ts @@ -0,0 +1,423 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +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 { + EngineRegistry, + createCustomEngineAdapter, + engineRegistry, + expandCommandTemplate, +} from "../src/engines/index.js"; +import { fetchLatestVersion, scanOutdatedDependencies } from "../src/outdated/checker.js"; +import { parsePackageSpec } from "../src/purl/parser.js"; +import { fetchRegistryMetadata } from "../src/security/registry.js"; +import { loadWorkspaceConfig } from "../src/workspace/config.js"; +import { verifyCompositeLockfile, writeCompositeLockfile } from "../src/workspace/lockfile.js"; + +test("Phase 5 PURL - Parses Hackage, CRAN, CPAN, and LuaRocks shorthands & RFC PURLs", () => { + const aeson = parsePackageSpec("hackage:aeson@2.2.3.0"); + assert.equal(aeson.ecosystem, "hackage"); + assert.equal(aeson.name, "aeson"); + assert.equal(aeson.version, "2.2.3.0"); + + const aesonPurl = parsePackageSpec("pkg:hackage/aeson@2.2.3.0"); + assert.equal(aesonPurl.ecosystem, "hackage"); + assert.equal(aesonPurl.name, "aeson"); + + const ggplot = parsePackageSpec("cran:ggplot2@3.5.1"); + assert.equal(ggplot.ecosystem, "cran"); + assert.equal(ggplot.name, "ggplot2"); + assert.equal(ggplot.version, "3.5.1"); + + const dplyrPurl = parsePackageSpec("pkg:cran/dplyr@1.1.4"); + assert.equal(dplyrPurl.ecosystem, "cran"); + + const mojo = parsePackageSpec("cpan:Mojolicious@9.38"); + assert.equal(mojo.ecosystem, "cpan"); + assert.equal(mojo.name, "Mojolicious"); + assert.equal(mojo.version, "9.38"); + + const dbixPurl = parsePackageSpec("pkg:cpan/DBIx-Class@0.082843"); + assert.equal(dbixPurl.ecosystem, "cpan"); + + const lpeg = parsePackageSpec("luarocks:lpeg@1.1.0"); + assert.equal(lpeg.ecosystem, "luarocks"); + assert.equal(lpeg.name, "lpeg"); + assert.equal(lpeg.version, "1.1.0"); + + const sockPurl = parsePackageSpec("pkg:luarocks/luasocket@3.1.0"); + assert.equal(sockPurl.ecosystem, "luarocks"); +}); + +test("Phase 5 Engines - Resolves CLI args for cabal/stack, CRAN Rscript, cpanm, and luarocks", () => { + const cabal = engineRegistry.createEngine("hackage"); + const pkgHaskell = parsePackageSpec("hackage:aeson@2.2.3.0"); + assert.deepEqual(cabal.resolveAddArgs(pkgHaskell), { + command: "cabal", + args: ["install", "aeson", "--lib", "--constraint=aeson ==2.2.3.0"], + }); + assert.deepEqual(cabal.resolveInstallArgs(), { + command: "cabal", + args: ["build", "--only-dependencies"], + }); + + const tmpStack = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase5-stack-")); + try { + fs.writeFileSync(path.join(tmpStack, "stack.yaml"), "resolver: lts-22.0\n"); + const stack = engineRegistry.createEngine("hackage", { + cwd: tmpStack, + manifest: "package.yaml", + }); + assert.deepEqual(stack.resolveAddArgs(pkgHaskell), { + command: "stack", + args: ["install", "aeson-2.2.3.0"], + }); + } finally { + fs.rmSync(tmpStack, { recursive: true, force: true }); + } + + const cran = engineRegistry.createEngine("cran"); + const rPkg = parsePackageSpec("cran:ggplot2@3.5.1"); + assert.deepEqual(cran.resolveAddArgs(rPkg), { + command: "Rscript", + args: ["-e", "pak::pkg_install('ggplot2@3.5.1'); renv::snapshot(prompt = FALSE)"], + }); + assert.deepEqual(cran.resolveRemoveArgs(rPkg), { + command: "Rscript", + args: ["-e", "remove.packages('ggplot2')"], + }); + + const cpan = engineRegistry.createEngine("cpan"); + const perlPkg = parsePackageSpec("cpan:Mojolicious@9.38"); + assert.deepEqual(cpan.resolveAddArgs(perlPkg), { command: "cpanm", args: ["Mojolicious@9.38"] }); + assert.deepEqual(cpan.resolveInstallArgs(), { command: "cpanm", args: ["--installdeps", "."] }); + + const lua = engineRegistry.createEngine("luarocks"); + const luaPkg = parsePackageSpec("luarocks:lpeg@1.1.0"); + assert.deepEqual(lua.resolveAddArgs(luaPkg), { + command: "luarocks", + args: ["install", "lpeg", "1.1.0"], + }); + assert.deepEqual(lua.resolveInstallArgs(), { + command: "luarocks", + args: ["install", "--only-deps"], + }); +}); + +test("Phase 5 Custom Plugins - Loads [engines.custom.*] from poly.toml, expands templates, detects & locks", () => { + const wsDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase5-custom-")); + const bazelDir = path.join(wsDir, "svc-bazel"); + const zigDir = path.join(wsDir, "svc-zig"); + fs.mkdirSync(bazelDir, { recursive: true }); + fs.mkdirSync(zigDir, { recursive: true }); + + fs.writeFileSync( + path.join(wsDir, "poly.toml"), + [ + 'name = "custom-polyglot"', + "", + "[workspace]", + 'members = ["svc-bazel", "svc-zig"]', + "", + "[engines.custom.bazel]", + 'manifest = "MODULE.bazel"', + 'lockfile = "MODULE.bazel.lock"', + 'command = "bazel"', + 'aliases = ["bzl"]', + 'add = "mod tidy --dep={name}@{cleanVersion}"', + 'remove = "mod tidy --rm={name}"', + 'install = "fetch //..."', + 'update = "mod deps --update={name}"', + "", + "[engines.custom.zig]", + 'manifest = "*.zon"', + 'lockfile = "build.zig.zon.lock"', + 'command = "zig"', + 'add = ["fetch", "--save", "{name}@{cleanVersion}"]', + 'install = ["build", "--fetch"]', + "", + ].join("\n"), + ); + fs.writeFileSync( + path.join(bazelDir, "MODULE.bazel"), + 'bazel_dep(name = "rules_cc", version = "0.0.10")\n', + ); + fs.writeFileSync(path.join(bazelDir, "MODULE.bazel.lock"), "{}\n"); + fs.writeFileSync(path.join(zigDir, "build.zig.zon"), '.{ .name = "demo" }\n'); + + try { + const config = loadWorkspaceConfig(wsDir); + assert.ok(config?.engines?.custom?.bazel); + assert.ok(config?.engines?.custom?.zig); + + // Detection picks up both exact and glob custom manifests + assert.equal(detectContexts(bazelDir)[0]?.ecosystem, "bazel"); + assert.equal(detectContexts(zigDir)[0]?.ecosystem, "zig"); + + // Command template expansion omits dangling @ when version missing + const pkgNoVer = parsePackageSpec("bazel:rules_go"); + const pkgVer = parsePackageSpec("bzl:rules_cc@0.0.10"); + assert.deepEqual(expandCommandTemplate("mod tidy --dep={name}@{cleanVersion}", [], pkgVer), [ + "mod", + "tidy", + "--dep=rules_cc@0.0.10", + ]); + assert.deepEqual(expandCommandTemplate("mod tidy --dep={name}@{cleanVersion}", [], pkgNoVer), [ + "mod", + "tidy", + "--dep=rules_go", + ]); + + const bazelEngine = engineRegistry.createEngine("bazel"); + assert.deepEqual(bazelEngine.resolveAddArgs(pkgVer), { + command: "bazel", + args: ["mod", "tidy", "--dep=rules_cc@0.0.10"], + }); + assert.deepEqual(bazelEngine.resolveInstallArgs(), { + command: "bazel", + args: ["fetch", "//..."], + }); + + const zigEngine = engineRegistry.createEngine("zig"); + assert.deepEqual(zigEngine.resolveInstallArgs(), { + command: "zig", + args: ["build", "--fetch"], + }); + + const lock = writeCompositeLockfile(wsDir); + assert.equal(lock.members.length, 2); + assert.equal(verifyCompositeLockfile(wsDir).isDrifted, false); + } finally { + engineRegistry.unregister("bazel"); + engineRegistry.unregister("zig"); + fs.rmSync(wsDir, { recursive: true, force: true }); + } +}); + +test("Phase 5 Lazy-Load & Startup Gate - Loads ONLY workspace manifest adapters & starts zero-dep binary fast", async () => { + // 1. Verify zero external runtime dependencies in package.json + const pkgJson = JSON.parse( + fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8"), + ) as { dependencies?: Record }; + assert.equal(pkgJson.dependencies, undefined); + + // 2. Verify fresh EngineRegistry loads ONLY adapters whose manifests exist in the directory + const reg = new EngineRegistry(); + let cpanLoads = 0; + let hackageLoads = 0; + + reg.registerLazy( + { + id: "cpan", + ecosystem: "cpan", + aliases: ["perl"], + purlTypes: ["cpan"], + manifests: ["cpanfile"], + lockfiles: [], + defaultCli: "cpanm", + }, + "perl", + async () => { + cpanLoads++; + return [ + createCustomEngineAdapter("cpan", { + manifests: ["cpanfile"], + command: "cpanm", + }), + ]; + }, + ); + reg.registerLazy( + { + id: "hackage", + ecosystem: "hackage", + aliases: ["haskell"], + purlTypes: ["hackage"], + manifests: ["*.cabal"], + lockfiles: [], + defaultCli: "cabal", + }, + "haskell", + async () => { + hackageLoads++; + return [ + createCustomEngineAdapter("hackage", { + manifests: ["*.cabal"], + command: "cabal", + }), + ]; + }, + ); + + const perlOnlyDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase5-lazy-")); + try { + fs.writeFileSync(path.join(perlOnlyDir, "cpanfile"), "requires 'Mojolicious', '9.38';\n"); + assert.equal(reg.isAdapterLoaded("cpan"), false); + assert.equal(reg.isAdapterLoaded("hackage"), false); + + const activated = await reg.loadForDirectory(perlOnlyDir); + assert.deepEqual(activated, ["cpan"]); + assert.equal(cpanLoads, 1); + assert.equal(hackageLoads, 0); + assert.equal(reg.isAdapterLoaded("cpan"), true); + assert.equal(reg.isAdapterLoaded("hackage"), false); + } finally { + fs.rmSync(perlOnlyDir, { recursive: true, force: true }); + } + + // 3. Verify compiled CLI bootstrap starts with 0 adapters eagerly instantiated and executes --version fast + const distCli = path.join(process.cwd(), "dist", "cli.js"); + if (fs.existsSync(distCli)) { + const t0 = performance.now(); + const versionOut = execFileSync(process.execPath, [distCli, "--version"], { + encoding: "utf-8", + }); + const elapsedMs = performance.now() - t0; + assert.ok(versionOut.trim().length > 0); + assert.ok(elapsedMs < 2000, `Expected fast CLI startup, took ${Math.round(elapsedMs)}ms`); + } +}); + +test("Phase 5 Integration - Registries, outdated/upgrader, poly.lock, OSV (Hackage & CRAN), SBOM & Doctor", async () => { + const wsDir = fs.mkdtempSync(path.join(os.tmpdir(), "poly-phase5-ws-")); + const hsDir = path.join(wsDir, "svc-haskell"); + const rDir = path.join(wsDir, "sci-r"); + const perlDir = path.join(wsDir, "svc-perl"); + const luaDir = path.join(wsDir, "ext-lua"); + + for (const d of [hsDir, rDir, perlDir, luaDir]) { + fs.mkdirSync(d, { recursive: true }); + } + + fs.writeFileSync( + path.join(hsDir, "demo.cabal"), + "name: demo\nlibrary\n build-depends:\n base >= 4.18,\n aeson >= 2.1.0\n", + ); + fs.writeFileSync(path.join(hsDir, "cabal.project.freeze"), "constraints: aeson ==2.1.0\n"); + fs.writeFileSync( + path.join(rDir, "DESCRIPTION"), + "Package: Analytics\nImports:\n ggplot2 (>= 3.4.0),\n dplyr (>= 1.1.0)\n", + ); + fs.writeFileSync( + path.join(rDir, "renv.lock"), + JSON.stringify({ + R: { Version: "4.4.0" }, + Packages: { ggplot2: { Package: "ggplot2", Version: "3.4.0" } }, + }), + ); + fs.writeFileSync(path.join(perlDir, "cpanfile"), "requires 'Mojolicious', '9.30';\n"); + fs.writeFileSync( + path.join(luaDir, "gateway-1.0-1.rockspec"), + 'package = "gateway"\ndependencies = {\n "lua >= 5.1",\n "lpeg >= 1.0.2"\n}\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("hackage.haskell.org/package/aeson/preferred.json")) { + return new Response(JSON.stringify({ "normal-version": ["2.2.3.0", "2.1.0"] }), { + status: 200, + }); + } + if (u.includes("crandb.r-pkg.org/ggplot2")) { + return new Response( + JSON.stringify({ + Version: "3.5.1", + License: "MIT + file LICENSE", + "Date/Publication": "2025-01-10", + }), + { status: 200 }, + ); + } + if (u.includes("fastapi.metacpan.org/v1/release/Mojolicious")) { + return new Response( + JSON.stringify({ version: "9.38", date: "2025-02-01T00:00:00Z", license: ["artistic_2"] }), + { status: 200 }, + ); + } + if (u.includes("luarocks.org/modules/luarocks/lpeg.json")) { + return new Response(JSON.stringify({ version: "1.1.0", license: "MIT" }), { 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 === "Hackage" && q.package?.name === "aeson" + ? { vulns: [{ id: "HSEC-aeson-test", summary: "Mock Hackage advisory" }] } + : {}, + ); + return new Response(JSON.stringify({ results }), { status: 200 }); + } + return new Response("{}", { status: 200 }); + }) as typeof fetch; + + try { + assert.equal(detectContexts(hsDir)[0]?.ecosystem, "hackage"); + assert.equal(detectContexts(rDir)[0]?.ecosystem, "cran"); + assert.equal(detectContexts(perlDir)[0]?.ecosystem, "cpan"); + assert.equal(detectContexts(luaDir)[0]?.ecosystem, "luarocks"); + + const dispatcher = new PolyDispatcher(); + assert.equal(dispatcher.which("hackage", hsDir).effectiveCli, "cabal"); + assert.equal(dispatcher.which("cran", rDir).effectiveCli, "Rscript"); + assert.equal(dispatcher.which("cpan", perlDir).effectiveCli, "cpanm"); + assert.equal(dispatcher.which("luarocks", luaDir).effectiveCli, "luarocks"); + + const lock = writeCompositeLockfile(wsDir); + assert.equal(lock.members.length, 4); + 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:hackage/aeson@2.1.0"))); + assert.ok(purls.some((p) => p.startsWith("pkg:cran/ggplot2@3.4.0"))); + assert.ok(purls.some((p) => p.startsWith("pkg:cpan/Mojolicious@9.30"))); + assert.ok(purls.some((p) => p.startsWith("pkg:luarocks/lpeg@1.0.2"))); + + assert.equal(await fetchLatestVersion("aeson", "hackage"), "2.2.3.0"); + assert.equal(await fetchLatestVersion("ggplot2", "cran"), "3.5.1"); + assert.equal(await fetchLatestVersion("Mojolicious", "cpan"), "9.38"); + assert.equal(await fetchLatestVersion("lpeg", "luarocks"), "1.1.0"); + + const cranMeta = await fetchRegistryMetadata("cran", "ggplot2"); + assert.equal(cranMeta?.latestVersion, "3.5.1"); + const cpanMeta = await fetchRegistryMetadata("cpan", "Mojolicious"); + assert.equal(cpanMeta?.latestVersion, "9.38"); + + const outdated = await scanOutdatedDependencies(wsDir); + assert.equal(outdated.outdatedCount, 4); + + // OSV queries Hackage and CRAN while gracefully skipping cpan and luarocks + const audit = await new CrossStackAuditor().audit(wsDir); + assert.ok( + osvQueries.some((q) => q.package?.ecosystem === "Hackage" && q.package?.name === "aeson"), + ); + assert.ok( + osvQueries.some((q) => q.package?.ecosystem === "CRAN" && q.package?.name === "ggplot2"), + ); + assert.ok(!osvQueries.some((q) => q.package?.ecosystem === "cpan")); + assert.ok(!osvQueries.some((q) => q.package?.ecosystem === "luarocks")); + assert.ok(audit.findings.some((f) => f.id === "HSEC-aeson-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 }); + } +});