import { readFile } from "node:fs/promises"; import path from "node:path"; import { loadQuixosLock, parseQuixosLockDocument, resolveQuixosLock } from "../resource-lock/index.js"; import { editStructure } from "./structural-edits.js"; import { workspaceSourcePin, type WorkspaceSourcePin } from "./source-closure.js"; /** Inspect/rewrite the root and its declared imports only, using the same lock * grammar as compilation. Return proposed file contents; publishing them and * selecting a Graph remain the caller's separate responsibilities. */ export async function workspaceSourceLocks(directory: string, input: unknown = []) { if (!Array.isArray(input) || input.length > 256) throw Error("Invalid source lock replacements"); const replacements = new Map(); const key = (source: WorkspaceSourcePin) => `${source.repository}\0${source.commit}`; for (const entry of input) { if (!entry || typeof entry !== "object") throw Error("Invalid source lock replacement"); const from = workspaceSourcePin(entry.from), to = workspaceSourcePin(entry.to); if (replacements.has(key(from))) throw Error("Duplicate source lock replacement"); replacements.set(key(from), to); } const lock = await loadQuixosLock(path.join(directory, "quixos.lock")); if (!lock.ok) throw Error(`Invalid source lock: ${lock.diagnostics.map((d) => d.message).join("; ")}`); const files = new Map(); for (const filename of lock.lock.sourceFiles!) { let source = await readFile(path.join(directory, filename), "utf8"); const parsed = parseQuixosLockDocument(source, filename); if (!parsed.ok) throw Error("Source lock changed during inspection"); for (const dependency of parsed.document.resources) { const replacement = replacements.get(key(dependency.source)); if (replacement) source = editStructure(source, { operation: "dependency", kind: dependency.kind, name: dependency.binding, source: replacement, }); } files.set(filename, source); } const checked = await resolveQuixosLock(files.get("quixos.lock")!, async (filename) => { const source = files.get(filename); if (source === undefined) throw Error("Source lock import changed during inspection"); return source; }); if (!checked.ok) throw Error(`Invalid rewritten source locks: ${checked.diagnostics.map((d) => d.message).join("; ")}`); return { lock: checked.lock, files: [...files].map(([path, source]) => ({ path, source })) }; }