import { randomBytes } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { configDir, type StimContext } from '@stim-cli/core'; import { isJsonObject, loadConfig, lockfileIntegrity, parsePluginPackageEntry, PLUGIN_INSTALL_RECORD, pluginInstallFolder, pluginInstallProblem, pluginInstalls, pluginPackageDir, pluginShortName, pluginsRoot, readPluginInstallRecord, type PluginInstall, type PluginInstallRecord, } from '@stim-cli/core/state'; import { compareVersions } from '../bin/route.mjs'; import { npmEnv } from './engine-store/npm.ts'; import { cloneTree, removeTree, setWritable } from './engine-store/tree.ts'; import { WorkspaceProcessCleanupError, withWorkspaceProcessLock } from './engine/workspace-process-lock.ts'; import { phaseLine } from './command-output.ts'; import { getExecutor } from './exec.ts'; import { fullPluginPackage, readProjectPlugins, type ProjectPluginEntry } from './integrations/plugin-projects.ts'; import { bundledProjectIds } from './integrations/projects.ts'; import { containedModule, PROJECT_API_VERSION, readProjectPlugin } from './project-plugin.ts'; import { knownPluginPackage } from './integrations/known-plugins.ts'; import { updateMachinePluginsAsync } from './workspace/config.ts'; const NPM_TIMEOUT_MS = 10 * 60_000; const LOCK_WAIT_MS = 15 * 60_000; const SNAPSHOT_LOCK_WAIT_MS = 10_000; const STAGING_PREFIX = '.staging-'; export class PluginStoreRefusal extends Error { readonly code: string; readonly remedy: string; constructor(code: string, message: string, remedy: string) { super(message); this.code = code; this.remedy = remedy; } } const refused = (message: string, remedy: string) => new PluginStoreRefusal('STIM_PLUGIN_REFUSED', message, remedy); const badArg = (message: string, remedy: string) => new PluginStoreRefusal('STIM_BAD_ARG', message, remedy); async function npm(args: string[], cwd: string, env: NodeJS.ProcessEnv): Promise { return getExecutor().runFileAsync('npm', args, { cwd, timeoutMs: NPM_TIMEOUT_MS, env: npmEnv(env) }); } function npmFailure(step: string, error: unknown): string { const stderr = isJsonObject(error) && typeof error.stderr === 'string' ? error.stderr : ''; const text = (stderr.trim() || (error instanceof Error ? error.message : String(error))).split('\n'); return `${step} failed: ${text.slice(-8).join('\n')}`; } /** The package a `stim plugin add` argument names, refusing a short name and anything but an exact version. */ function addSpec(given: string): { package: string; version: string | null } { const parsed = parsePluginPackageEntry(given); if (!parsed || parsed.package.startsWith('-')) throw badArg( `${JSON.stringify(given)} is not an npm package name, optionally with an exact version.`, 'Name the full package, such as @stim-cli/plugin-godot or @stim-cli/plugin-godot@1.0.0.', ); const full = knownPluginPackage(parsed.package); if (full !== null) { throw badArg( `stim plugin add takes the full package name, not the short name ${parsed.package}.`, `Run stim plugin add ${full}${parsed.version ? `@${parsed.version}` : ''}.`, ); } return parsed; } /** The installs whose package `name` names, as a package or as the short name an install goes by. */ function installsOf(name: string, installs: readonly PluginInstall[]): PluginInstall[] { const exact = installs.filter((install) => install.package === name); return exact.length ? exact : installs.filter((install) => pluginShortName(install.package) === name); } /** Whether the `plugins` entry `entry` names the package `pkg`, by any of its forms. */ function namesPackage(entry: unknown, pkg: string): boolean { const parsed = typeof entry === 'string' ? parsePluginPackageEntry(entry) : null; return ( parsed !== null && (parsed.package === pkg || fullPluginPackage(parsed.package) === pkg || (parsed.version === null && parsed.package === pluginShortName(pkg))) ); } interface Staged { dir: string; version: string; integrity: string; /** Set when the package speaks a project integer newer than this Stim's. */ newerKind?: number; problem?: string; } // @ref LLP 0023#plugins-installed-from-npm -- what an install must hold before it is renamed into place function validateStaged(staging: string, pkg: string): Staged | { problem: string } { const dir = pluginPackageDir(staging, pkg); let manifest: unknown; let lock: unknown; try { manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); lock = JSON.parse(readFileSync(join(staging, 'package-lock.json'), 'utf8')); } catch { return { problem: `npm installed no ${pkg} with a lockfile` }; } if (!isJsonObject(manifest) || manifest.name !== pkg || typeof manifest.version !== 'string') return { problem: `npm installed a package.json that is not ${pkg}` }; const integrity = lockfileIntegrity(staging, pkg); if (!integrity) return { problem: `the lockfile npm wrote holds no integrity for ${pkg}` }; const locked = isJsonObject(lock) && isJsonObject(lock.packages) ? lock.packages[`node_modules/${pkg}`] : null; if ( parsePluginPackageEntry(`${pkg}@${manifest.version}`)?.version !== manifest.version || !isJsonObject(locked) || locked.version !== manifest.version ) return { problem: `the package.json of ${pkg} names a version the lockfile does not` }; const staged = { dir, version: manifest.version, integrity }; const stim = isJsonObject(manifest.stimPlugin) ? manifest.stimPlugin : null; const kind = stim && isJsonObject(stim.kinds) ? stim.kinds.project : undefined; if (typeof kind === 'number' && Number.isInteger(kind) && kind > PROJECT_API_VERSION) return { ...staged, newerKind: kind, problem: `${pkg}@${manifest.version} speaks project ${kind}, and this Stim speaks project ${PROJECT_API_VERSION}`, }; const read = readProjectPlugin(dir, bundledProjectIds()); const module = read.project?.module; const found = module === undefined ? null : containedModule(dir, module); const error = read.checks.find((check) => check.error !== null)?.error ?? (found && 'error' in found ? found.error : null); return error ? { ...staged, problem: `${pkg}@${manifest.version} is not a project plugin Stim accepts: ${error}` } : staged; } /** The install folder for `pkg@version` when it exists and is not an install Stim made, or null. */ // @ref LLP 0023#plugins-installed-from-npm -- Stim deletes or replaces only a folder whose install.json it wrote function foreignFolder(pkg: string, version: string): string | null { const target = join(pluginsRoot(), pluginInstallFolder(pkg, version)); return existsSync(target) && !pluginInstalls().some((install) => install.dir === target) ? target : null; } function sweepStaging(root: string): void { for (const name of readdirSync(root)) if (name.startsWith(STAGING_PREFIX)) removeTree(join(root, name)); } /** * Installs `pkg` at `version` (the registry's latest when null) into a staging folder, checks it, and returns it * unsealed; the caller seals it with `place` or removes it. Runs under the store lock. */ // @ref LLP 0023#plugins-installed-from-npm -- one npm install with the user's npm configuration, scripts off async function stage( pkg: string, version: string | null, env: NodeJS.ProcessEnv, log: (line: string) => void, ): Promise { const staging = join(pluginsRoot(), `${STAGING_PREFIX}${process.pid}-${randomBytes(4).toString('hex')}`); mkdirSync(staging); try { writeFileSync( join(staging, 'package.json'), `${JSON.stringify({ private: true, description: 'Installed by stim plugin add; Stim owns this folder.' }, null, 2)}\n`, ); const spec = `${pkg}@${version ?? 'latest'}`; log(phaseLine('install', spec)); await npm( [ 'install', '--ignore-scripts', '--omit=dev', '--save=true', '--save-exact', '--global=false', '--location=project', '--package-lock=true', spec, ], staging, env, ).catch((error: unknown) => { throw refused( npmFailure('npm install', error), `Check that ${spec} exists on your npm registry, then run this again.`, ); }); const staged = validateStaged(staging, pkg); if (!('version' in staged)) throw refused(`${staged.problem}.`, 'Nothing was installed.'); if (version !== null && staged.version !== version) throw refused(`npm installed ${pkg}@${staged.version}, not ${version}.`, 'Nothing was installed.'); const foreign = foreignFolder(pkg, staged.version); if (foreign) throw refused( `${foreign} already exists and is not a folder stim plugin add made, so Stim leaves it alone.`, 'Move or rename that folder, then run this again.', ); return { ...staged, staging }; } catch (error) { removeTree(staging); throw error; } } /** Writes `install.json`, makes the staged tree read-only and renames it to its install folder. */ function place(staged: Staged & { staging: string }, pkg: string): string { const target = join(pluginsRoot(), pluginInstallFolder(pkg, staged.version)); if (dirname(target) !== pluginsRoot() || foreignFolder(pkg, staged.version)) throw new Error(`Stim does not own ${target}`); const record: PluginInstallRecord = { package: pkg, version: staged.version, integrity: staged.integrity, installedAt: new Date().toISOString(), }; writeFileSync(join(staged.staging, PLUGIN_INSTALL_RECORD), `${JSON.stringify(record, null, 2)}\n`); setWritable(staged.staging, false); if (existsSync(target)) removeTree(target); renameSync(staged.staging, target); return target; } async function withStore(fn: () => Promise): Promise { mkdirSync(pluginsRoot(), { recursive: true }); // @ref LLP 0023#plugins-installed-from-npm -- one writer of the install folder at a time return withWorkspaceProcessLock( configDir(), 'plugins', async () => { sweepStaging(pluginsRoot()); return fn(); }, { external: true, waitMs: LOCK_WAIT_MS }, ); } // @ref LLP 0009#plugin-builds -- a build loads its own copy of the install, taken under the store lock /** * Copies the install folder `source` to `target`, which must not exist, under the store lock: a copy-on-write clone * where the volume can, else a copy. Returns why the copy is not a sound install of `wanted`, and then leaves no * copy, or null. The copy is writable, so whoever removes `target`'s parent removes it. It waits for the lock only * briefly, since an add holds it through npm, and then throws with the code `STIM_LOCK_TIMEOUT`. Unlike a store * command, it never sweeps `.staging-*` folders, which may be a user's own. */ export async function snapshotPluginInstall( source: string, target: string, wanted: { package: string; version: string; integrity: string }, ctx: StimContext, ): Promise { return withWorkspaceProcessLock( configDir(), 'plugins', async () => { try { await cloneTree(source, target, ctx); setWritable(target, true); } catch (error) { if (error instanceof WorkspaceProcessCleanupError || (error instanceof Error && 'reportCleanup' in error)) throw error; if (existsSync(target)) removeTree(target); return `the install of ${wanted.package}@${wanted.version} could not be copied: ${error instanceof Error ? error.message : String(error)}`; } const record = readPluginInstallRecord(target); if ( record?.package === wanted.package && record.version === wanted.version && record.integrity === wanted.integrity && !pluginInstallProblem({ package: record.package, version: record.version, dir: target, record }) ) return null; removeTree(target); return `the install of ${wanted.package}@${wanted.version} changed before this build copied it`; }, { external: true, signal: ctx.signal, waitMs: SNAPSHOT_LOCK_WAIT_MS }, ); } const resolved = (entries: readonly unknown[]): Map => new Map(readProjectPlugins(entries, bundledProjectIds()).map((entry) => [entry.reference, entry])); /** How the machine `plugins` entries resolve now; taken before a new install is placed, for `select`. */ function resolvedNow(): Map { const plugins = loadConfig()?.plugins; return resolved(Array.isArray(plugins) ? plugins : []); } /** * Points the `plugins` entries that name `pkg` at `pkg@version`, in place, appending one when none does and `append` * is set, and removes its other install folders. Returns why the change would reject the new entry or one `before` * accepted, and changes nothing then. */ // @ref LLP 0023#plugins-installed-from-npm -- a pin moves only when no entry the resolver accepted becomes rejected async function select( pkg: string, version: string, append: boolean, before: Map, ): Promise { const entry = `${pkg}@${version}`; let problem: string | null = null; await updateMachinePluginsAsync((entries) => { const at = entries.findIndex((each) => namesPackage(each, pkg)); if (at === -1 && !append) return entries; const after = at === -1 ? [...entries, entry] : entries.flatMap((each, index) => (index === at ? [entry] : namesPackage(each, pkg) ? [] : [each])); const broken = [...resolved(after).values()].find( (each) => each.problem !== null && (each.reference === entry || before.get(each.reference)?.problem === null), ); problem = broken ? `${broken.reference}: ${broken.problem}` : null; return problem === null ? after : entries; }); if (problem !== null) return problem; for (const install of pluginInstalls()) if (install.package === pkg && install.version !== version) removeTree(install.dir); return null; } const keptSetting = 'The plugins setting and the installed version are unchanged.'; export interface PluginChange { package: string; version: string; /** The version it replaced, or null. */ previous: string | null; dir: string; } // @ref LLP 0023#plugins-installed-from-npm -- add installs the full package name and writes @ export async function addPlugin( given: string, { env, log }: { env: NodeJS.ProcessEnv; log: (line: string) => void }, ): Promise { const { package: pkg, version } = addSpec(given); return withStore(async () => { const before = pluginInstalls().filter((install) => install.package === pkg); const same = version === null ? undefined : before.find((install) => install.version === version); const previous = before.find((install) => install.version !== version)?.version ?? null; if (same && pluginInstallProblem(same) === null) { const problem = await select(pkg, same.version, true, resolvedNow()); if (problem) throw refused(`${problem}.`, keptSetting); return { package: pkg, version: same.version, previous, dir: same.dir }; } const staged = await stage(pkg, version, env, log); if (staged.problem) { removeTree(staged.staging); throw refused( `${staged.problem}.`, staged.newerKind !== undefined ? `Run stim engine update, then stim plugin add ${pkg} again.` : 'Nothing was installed.', ); } const current = before.find((install) => install.version === staged.version); const accepted = resolvedNow(); let dir: string; const placed = !(current && pluginInstallProblem(current) === null); if (placed) dir = place(staged, pkg); else { removeTree(staged.staging); dir = current.dir; } const problem = await select(pkg, staged.version, true, accepted); if (problem) { if (placed) removeTree(dir); throw refused(`${problem}.`, keptSetting); } return { package: pkg, version: staged.version, previous: previous === staged.version ? null : previous, dir }; }); } export interface PluginRemoval { entries: string[]; installs: string[]; } // @ref LLP 0023#plugins-installed-from-npm -- remove takes any form that names a package, short names included export async function removePlugin(given: string): Promise { const parsed = parsePluginPackageEntry(given); if (!parsed) throw badArg( `${JSON.stringify(given)} does not name a plugin package.`, 'Name an installed plugin by package, package@version or short name; take a directory entry out with stim settings set plugins --scope machine.', ); return withStore(async () => { const matched = installsOf(parsed.package, pluginInstalls()).filter( (install) => parsed.version === null || install.version === parsed.version, ); const pkg = matched[0]?.package ?? fullPluginPackage(parsed.package); const gone = new Set(matched.map(({ dir }) => dir)); const removed: string[] = []; await updateMachinePluginsAsync((entries) => { const current = resolved(entries); return entries.filter((entry) => { const version = typeof entry === 'string' ? parsePluginPackageEntry(entry)?.version : undefined; const named = entry === given || (namesPackage(entry, pkg) && (parsed.version === null || version === parsed.version || (version === null && gone.has(current.get(String(entry))?.install?.dir ?? '')))); if (named) removed.push(String(entry)); return !named; }); }); for (const install of matched) removeTree(install.dir); if (!removed.length && !matched.length) throw badArg( `No plugins entry or install names ${given}.`, 'Run stim plugin list to see the plugins Stim knows.', ); return { entries: removed, installs: matched.map(({ dir }) => dir) }; }); } export type PluginUpdate = | ({ status: 'updated' } & PluginChange) | { status: 'current'; package: string; version: string } | { status: 'kept'; package: string; version: string; latest: string | null; reason: string; remedy: string }; // @ref LLP 0023#plugins-installed-from-npm -- a newer version this Stim cannot load leaves the installed one in place export async function updatePlugins( given: string | undefined, { env, log }: { env: NodeJS.ProcessEnv; log: (line: string) => void }, ): Promise { return withStore(async () => { const installs = pluginInstalls().toSorted( (a, b) => a.package.localeCompare(b.package) || (compareVersions(b.version, a.version) ?? 0), ); const targets = ( given === undefined ? installs : installsOf(parsePluginPackageEntry(given)?.package ?? given, installs) ).filter((install, at, all) => all.findIndex((each) => each.package === install.package) === at); if (!targets.length) throw badArg( given === undefined ? 'No plugin is installed from npm.' : `No install of ${given} is found.`, 'Install one with stim plugin add .', ); const results: PluginUpdate[] = []; log(phaseLine('check', `${targets.length} ${targets.length === 1 ? 'plugin' : 'plugins'} against the registry`)); for (const install of targets) { const { package: pkg, version } = install; let latest: string | null = null; let staged: Awaited>; try { latest = ( await npm(['view', `${pkg}@latest`, 'version', '--json=false'], pluginsRoot(), env).catch( (error: unknown) => { throw refused( npmFailure('npm view', error), `Check that ${pkg} is on your npm registry, then run this again.`, ); }, ) ).trim(); if (latest === version) { results.push({ status: 'current', package: pkg, version }); continue; } staged = await stage(pkg, latest, env, log); } catch (error) { if (!(error instanceof PluginStoreRefusal)) throw error; results.push({ status: 'kept', package: pkg, version, latest, reason: error.message, remedy: error.remedy }); continue; } if (staged.problem) { removeTree(staged.staging); results.push({ status: 'kept', package: pkg, version, latest, reason: staged.problem, remedy: staged.newerKind !== undefined ? `Run stim engine update, then stim plugin update ${pkg}.` : `Report it to the publisher of ${pkg}; ${version} stays installed.`, }); continue; } const accepted = resolvedNow(); const dir = place(staged, pkg); const problem = await select(pkg, staged.version, false, accepted); if (problem) { removeTree(dir); results.push({ status: 'kept', package: pkg, version, latest, reason: problem, remedy: keptSetting }); continue; } results.push({ status: 'updated', package: pkg, version: staged.version, previous: version, dir }); } return results; }); }