import "server-only"; import { getViewer } from "@/lib/auth"; import { canWrite, findRepo, repoAccess, type Access } from "@/lib/repos"; export class ActionError extends Error {} export async function viewerOrThrow() { const viewer = await getViewer(); if (!viewer) throw new ActionError("You must be signed in to do that."); return viewer; } /** Loads a repository for a server action and checks the viewer's access level. */ export async function repoForAction(owner: string, name: string, need: "read" | "write" | "admin") { const viewer = await viewerOrThrow(); const repo = findRepo(owner, name); const access: Access = repo ? repoAccess(repo, viewer.id) : null; if (!repo || !access) throw new ActionError("Repository not found."); if (need === "write" && !canWrite(access)) throw new ActionError("You don't have push access to this repository."); if (need === "admin" && access !== "admin") throw new ActionError("Only the owner can change these settings."); return { repo, viewer, access }; }