import type { Actor, Person } from "./contract/actor.ts"; import type { Outcome } from "./contract/common.ts"; import { refsErrorCode, refsErrorDescription } from "./contract/errors.ts"; import type { Refs } from "./contract/handles.ts"; import { openRefs } from "./handles/refs.ts"; import { Policy } from "./policy.ts"; import { memberNamespaces, namespaceBySlug, namespacePolicy } from "./repos.ts"; import { recordRunFinished } from "./sessions.ts"; const REPO_ROUTE = /^\/api\/cli\/repos\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/(pulls|tasks|runs)(?:\/([^/]+))?(?:\/([a-z]+))?(?:\/([^/]+))?$/; type Json = Record; const text = (value: unknown): string => (typeof value === "string" ? value : ""); function settled(outcome: Outcome): Response { return outcome.ok ? Response.json(outcome.value ?? {}) : Response.json({ error: outcome.problem.message }, { status: 422 }); } /** The refs handle of the signed-in person, at home in `namespace`, under the same rules as the web. */ async function refsFor(env: Env, ctx: ExecutionContext, origin: string, person: Person, namespace: string): Promise { const actor: Actor = { kind: "human", person, via: "cli" }; const base = new Policy(actor, null); const [mine, home] = await Promise.all([memberNamespaces(env.DB, actor), namespaceBySlug(env.DB, namespace)]); const policy = home ? await namespacePolicy(env.DB, base, home.id) : base; return openRefs({ env, ctx, origin }, policy, home, mine); } /** The `gh`-style commands of the refs CLI: pull requests, tasks and CI runs of one repository. */ async function repoApi(refs: Refs, name: string, method: string, url: URL, route: (string | undefined)[], input: () => Promise): Promise { const [kind, id, action, extra] = route; const repo = await refs.repo(name); const state = url.searchParams.get("state") === "closed" ? "closed" : "open"; if (kind === "pulls" && !id && method === "GET") return Response.json(await repo.pulls({ status: state })); if (kind === "pulls" && !id && method === "POST") { const body = await input(); const base = text(body.base) || (await repo.refs()).defaultRef || ""; return settled(await repo.openPull({ title: text(body.title), body: text(body.body), base, head: text(body.head) })); } if (kind === "pulls" && id && !action && method === "GET") { const pull = await repo.pull(Number(id)); const [threads, mergeability, checks] = await Promise.all([pull.threads(), pull.detail.status === "open" ? pull.mergeability() : null, repo.ci().runs({ pull: pull.detail.number, limit: 5 })]); return Response.json({ ...pull.detail, threads: threads.filter((thread) => thread.status !== "resolved").length, mergeability, checks }); } if (kind === "pulls" && id && action === "merge" && method === "POST") return settled(await (await repo.pull(Number(id))).merge()); if (kind === "tasks" && !id && method === "GET") return Response.json(await refs.tasks({ status: state, repo: name })); if (kind === "tasks" && !id && method === "POST") { const body = await input(); return settled(await refs.createTask({ title: text(body.title), body: text(body.body), repo: name, assignee: null, labels: [] })); } if (kind === "tasks" && id && !action && method === "GET") return Response.json((await refs.task(name, Number(id))).detail); if (kind === "runs" && id && !action && method === "GET") return Response.json(await repo.ci().run(id)); if (kind === "runs" && id && action === "logs" && extra && method === "GET") return Response.json(await repo.ci().logs(id, decodeURIComponent(extra))); return new Response("Not found\n", { status: 404 }); } /** The refs CLI's API. Every request carries an OAuth access token, checked before this handler runs. */ export const cliApi = { async fetch(request, env, ctx) { const { props, auth } = ctx as ExecutionContext & { props?: { userId?: string }; auth?: { scope?: string[] } }; const userId = props?.userId; if (!userId) return new Response("Unauthorized\n", { status: 401 }); const url = new URL(request.url); const { pathname } = url; if (pathname === "/api/cli/connect") { const headers = new Headers(request.headers); headers.set("x-refs-user", userId); return env.USER_HUB.get(env.USER_HUB.idFromName(userId)).fetch(new Request(request, { headers })); } const person = await env.DB.prepare("SELECT id, name, email FROM users WHERE id = ?").bind(userId).first(); if (!person) return new Response("Not found\n", { status: 404 }); if (pathname === "/api/cli/whoami") return Response.json(person); if (pathname === "/api/cli/runs/finished" && request.method === "POST") { const recorded = await recordRunFinished(env, userId, (await request.json().catch(() => ({}))) as Json); return recorded ? new Response(null, { status: 204 }) : new Response("No such run\n", { status: 404 }); } const route = REPO_ROUTE.exec(pathname); const creating = pathname === "/api/cli/repos" && request.method === "POST"; if (!route && !creating) return new Response("Not found\n", { status: 404 }); if (!auth?.scope?.includes("git")) return Response.json({ error: "This sign-in cannot act as you. Run `refs login`." }, { status: 403 }); if (!route) { const body = await request.json().catch((): Json => ({})); const owner = text(body.owner) || (await memberNamespaces(env.DB, { kind: "human", person, via: "cli" }))[0]?.slug || ""; const refs = await refsFor(env, ctx, url.origin, person, owner); return settled(await refs.createRepo({ owner, name: text(body.name), description: text(body.description), visibility: body.visibility === "public" ? "public" : "private", setUp: body.setUp !== false })); } const [, namespace, repo, ...rest] = route; try { const refs = await refsFor(env, ctx, url.origin, person, namespace!); return await repoApi(refs, `${namespace}/${repo}`, request.method, url, rest, () => request.json().catch(() => ({}))); } catch (error) { const code = refsErrorCode(error); if (!code) throw error; return Response.json({ error: refsErrorDescription(error) }, { status: code === "not_found" ? 404 : 403 }); } }, } satisfies ExportedHandler;