export type PathErrorInfo = | { kind: "invalid_cwd" } | { kind: "escapes_root"; input: string } | { kind: "not_absolute"; path: string };export class PathError extends Error { declare readonly kind: PathErrorInfo["kind"]; declare readonly input?: string; declare readonly path?: string; constructor(info: PathErrorInfo) { super(info.kind); Object.assign(this, info); }}const walk = (start: string[], path: string, input: string): string[] => { const out = [...start]; for (const seg of path.split("/")) { if (seg === "" || seg === ".") continue; if (seg === "..") { if (out.length === 0) throw new PathError({ kind: "escapes_root", input }); out.pop(); } else { out.push(seg); } } return out;};const join = (segs: string[]): string => "/" + segs.join("/");/** Throws PathError (invalid_cwd, escapes_root). */export function resolvePath(cwd: string, input: string): string { if (!cwd.startsWith("/")) throw new PathError({ kind: "invalid_cwd" }); const base = input.startsWith("/") ? [] : walk([], cwd, input); return join(walk(base, input, input));}/** Throws PathError (not_absolute, escapes_root). */export function relativeTo(from: string, to: string): string { if (!from.startsWith("/")) throw new PathError({ kind: "not_absolute", path: from }); if (!to.startsWith("/")) throw new PathError({ kind: "not_absolute", path: to }); const a = walk([], from, from); const b = walk([], to, to); let k = 0; while (k < a.length && k < b.length && a[k] === b[k]) k++; const parts = [...a.slice(k).map(() => ".."), ...b.slice(k)]; return parts.length === 0 ? "." : parts.join("/");}