histoire
Version:
A fast story book powered by Vite
153 lines (152 loc) • 7.24 kB
JavaScript
import { createHash } from 'node:crypto';
import { open, readFile } from 'node:fs/promises';
import path from 'pathe';
import { guardConfigFile, guardProjectPath } from '../../config/codemod/security.js';
import { hashConfigCode } from '../../config/codemod/write.js';
import { compareVersions } from '../catalog/version.js';
import { readInstalledPackage } from '../inventory/package-resolve.js';
import { editPluginConfig } from './config-edit.js';
import { hasManagedConfigInput } from './config-inputs.js';
import { fileDiff } from './diff.js';
import { manualPlan } from './manual.js';
import { optionEdits } from './options.js';
import { editPackageJson } from './package-edit.js';
import { detectPackageManager, findWorkspaceRoot, lockfiles, packageCommand } from './package-manager.js';
import { changeRequestSchema, exactVersion } from './validation.js';
/** Controlled planner error consumable by channel and job admission. */
export class PlanningError extends Error {
/** Public failure code. */
code;
/** Attaches a transport-safe code to a readable failure. */
constructor(code, message) {
super(message);
this.code = code;
}
}
/** Reads existing project bytes; absence alone is not an IO failure. */
async function optionalRead(file) {
try {
return await readFile(file, 'utf8');
}
catch (error) {
if (error.code === 'ENOENT')
return undefined;
throw error;
}
}
/** Computes fresh argv, exact source edits and a review hash without writes. */
export async function computePlan(options, input) {
const parsed = changeRequestSchema.safeParse(input);
if (!parsed.success)
throw new PlanningError('invalid', 'Invalid plugin change');
const plugin = await options.resolvePlugin(parsed.data);
const request = { ...parsed.data, version: parsed.data.version ?? plugin.version };
exactVersion.parse(request.version);
optionEdits(plugin.manifest.config.options ?? [], request.options);
const packageFile = await guardProjectPath(path.join(options.root, 'package.json'), options.root);
const packageBefore = await optionalRead(packageFile) ?? '{}\n';
const packageData = JSON.parse(packageBefore);
const packages = new Map([[packageFile, packageData]]);
const boundary = await findWorkspaceRoot(options.root, packages);
const manager = options.static ? undefined : await detectPackageManager(options.root, request.prefs.packageManager, boundary, packages);
const configFile = options.configFile && await guardConfigFile(options.configFile, { root: options.root });
const configBefore = configFile ? await optionalRead(configFile) : undefined;
const plan = {
planId: '',
hash: '',
packageManager: manager ? { name: manager.name, source: manager.source } : { name: request.prefs.packageManager === 'auto' ? 'npm' : request.prefs.packageManager, source: 'override' },
files: [],
warnings: [],
};
const result = {
plan,
request,
configHash: configBefore === undefined ? undefined : hashConfigCode(configBefore),
packageCode: packageBefore,
packageHash: hashConfigCode(packageBefore),
manifest: plugin.manifest,
};
const installed = request.kind === 'pin' ? await readInstalledPackage(options.root, request.id) : undefined;
if (typeof installed?.version === 'string' && compareVersions(request.version, installed.version) < 0) {
plan.warnings.push(`Pinning ${request.id} downgrades from ${installed.version} to ${request.version}. Config migrations are not applied.`);
}
let reason;
if (options.static)
reason = 'static';
else if (configBefore === undefined)
reason = 'config-not-literal';
else if (await hasManagedConfigInput(configFile, options.configDependencies?.()))
reason = 'config-not-literal';
else if (!manager)
reason = 'no-package-manager';
else if (request.migrate)
reason = 'migration-manual';
const ranges = ['dependencies', 'devDependencies', 'optionalDependencies'].map(key => packageData[key]?.[request.id]);
if (!reason && ranges.some(value => typeof value === 'string' && /^(?:workspace:|file:|link:|portal:)/.test(value)))
reason = 'workspace-unsupported';
if (!reason) {
try {
result.configCode = editPluginConfig(configBefore, request, plugin.manifest);
}
catch {
reason = 'config-not-literal';
}
}
if (reason) {
plan.manual = manualPlan(reason, request, plugin.manifest);
}
else {
plan.command = packageCommand(manager, request);
result.packageCode = editPackageJson(packageBefore, request);
if (result.configCode !== configBefore)
plan.files.push(fileDiff(path.relative(options.root, configFile), configBefore, result.configCode));
if (result.packageCode !== packageBefore)
plan.files.push(fileDiff('package.json', packageBefore, result.packageCode));
if (plan.command)
plan.warnings.push('Package manager may also change the lockfile and node_modules');
}
const lockPaths = [];
for (let directory = path.resolve(options.root);; directory = path.dirname(directory)) {
for (const name of [...lockfiles, 'pnpm-workspace.yaml'])
lockPaths.push(path.join(directory, name));
if (directory === boundary)
break;
}
// Bind the review to exact source bytes as well as displayed hunks. This also
// catches changes outside diff context, formatting, lockfiles and EOF newlines.
const hash = createHash('sha256').update(JSON.stringify({ argv: plan.command?.argv, files: plan.files, warnings: plan.warnings, installedVersion: installed?.version, configHash: result.configHash, configCode: result.configCode, packageHash: result.packageHash, packageCode: result.packageCode, manifest: plugin.manifest, manual: plan.manual }));
await hashLockfiles(hash, lockPaths, boundary);
plan.hash = hash.digest('hex');
return result;
}
/** Stream length-framed lock bytes into one hash; binary Bun locks stay distinct. */
async function hashLockfiles(hash, files, boundary) {
for (const file of files) {
const safe = await guardProjectPath(file, boundary);
let handle;
try {
handle = await open(safe, 'r');
}
catch (error) {
if (error.code !== 'ENOENT')
throw error;
hash.update(JSON.stringify([file, null]));
continue;
}
try {
const { size } = await handle.stat();
// Length frames prevent adjacent file contents from being interchangeable.
hash.update(JSON.stringify([file, size]));
let bytes = 0;
for await (const chunk of handle.createReadStream({ autoClose: false })) {
hash.update(chunk);
bytes += chunk.length;
}
if (bytes !== size)
throw new PlanningError('stale', 'Lockfile changed while planning');
}
finally {
await handle.close();
}
}
}