import { now } from "./auth.ts"; import type { Actor, Role } from "./contract/actor.ts"; import { MAX_DESCRIPTION_LENGTH } from "./contract/limits.ts"; import type { RepoSummary, Visibility } from "./contract/views.ts"; import { Policy, principal, type RepoFacts } from "./policy.ts"; export interface Namespace { id: string; slug: string; name: string; kind: "user" | "org"; } export interface RepoRecord { id: string; namespace_id: string; name: string; full_name: string; description: string; visibility: Visibility; default_branch: string; artifacts_name: string; creator_id: string; created_at: number; forked_from_url: string | null; forked_from_name: string | null; open_tasks: number; open_pulls: number; forks: number; } const REPO_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/; const RESERVED_SLUGS = new Set(["organizations", "switch", "new", "setup", "login", "logout", "signup", "waitlist", "invite", "settings", "tasks", "assets", "api", "mcp", "oauth", "install", "cli", "admin", "docs"]); const SELECT_REPO = "SELECT r.*, n.slug || '/' || r.name AS full_name, fn.slug || '/' || f.name AS forked_from_name, (SELECT count(*) FROM tasks t WHERE t.repo_id = r.id AND t.status = 'open') AS open_tasks, (SELECT count(*) FROM pulls p WHERE p.repo_id = r.id AND p.status = 'open') AS open_pulls, (SELECT count(*) FROM repos c WHERE c.forked_from_repo_id = r.id) AS forks FROM repos r JOIN namespaces n ON n.id = r.namespace_id LEFT JOIN repos f ON f.id = r.forked_from_repo_id LEFT JOIN namespaces fn ON fn.id = f.namespace_id"; export function repoFacts(record: RepoRecord): RepoFacts { return { name: record.full_name, visibility: record.visibility, creatorId: record.creator_id }; } export async function namespaceBySlug(db: D1Database, slug: string): Promise { return db.prepare("SELECT id, slug, name, kind FROM namespaces WHERE slug = ?").bind(slug).first(); } /** Every namespace the actor's human belongs to: their own account first, then organizations by name. */ export async function memberNamespaces(db: D1Database, actor: Actor): Promise { const person = principal(actor); if (!person) return []; const { results } = await db .prepare("SELECT n.id, n.slug, n.name, n.kind FROM memberships m JOIN namespaces n ON n.id = m.namespace_id WHERE m.user_id = ? ORDER BY n.kind = 'user' DESC, n.slug") .bind(person.id) .all(); return results; } export async function namespacePolicy(db: D1Database, base: Policy, namespaceId: string): Promise { const found = await db .prepare("SELECT n.kind, m.role FROM namespaces n LEFT JOIN memberships m ON m.namespace_id = n.id AND m.user_id = ? WHERE n.id = ?") .bind(base.person?.id ?? null, namespaceId) .first<{ kind: Namespace["kind"]; role: Role | null }>(); return base.withRole(found?.role ?? null, found?.kind === "user"); } export function splitFullName(fullName: string): { slug: string; name: string } | null { const [slug, name, ...rest] = fullName.split("/"); return slug && name && !rest.length ? { slug, name } : null; } export async function findRepoRecord(db: D1Database, fullName: string): Promise { const parts = splitFullName(fullName); if (!parts) return null; return db.prepare(`${SELECT_REPO} WHERE n.slug = ? AND r.name = ?`).bind(parts.slug, parts.name).first(); } export async function findRepoRecordById(db: D1Database, id: string): Promise { return db.prepare(`${SELECT_REPO} WHERE r.id = ?`).bind(id).first(); } export async function listRepoRecords(db: D1Database, namespaceId: string): Promise { const { results } = await db.prepare(`${SELECT_REPO} WHERE r.namespace_id = ? ORDER BY r.name COLLATE NOCASE`).bind(namespaceId).all(); return results; } export function toSummary(record: RepoRecord, policy: Policy, origin: string): RepoSummary { const facts = repoFacts(record); return { name: record.full_name, description: record.description, visibility: record.visibility, createdAt: record.created_at, openTasks: record.open_tasks, openPulls: record.open_pulls, forks: record.forks, origin: record.forked_from_url ? { kind: "import", url: record.forked_from_url } : record.forked_from_name ? { kind: "fork", repo: record.forked_from_name } : null, cloneUrl: `${origin}/${record.full_name}.git`, can: { write: policy.canWriteRepo(facts), admin: policy.canAdminRepo(facts) }, }; } export function repoNameError(name: string): string | undefined { if (!REPO_NAME_PATTERN.test(name)) return "Use 1–100 letters, numbers, '.', '-' or '_', starting with a letter or number."; if (name.toLowerCase().endsWith(".git")) return "Repository names can't end in .git."; } export function slugError(slug: string): string | undefined { if (!SLUG_PATTERN.test(slug)) return "Use 1–39 lowercase letters, numbers or '-', starting and ending with a letter or number."; if (RESERVED_SLUGS.has(slug)) return `"${slug}" is reserved.`; } /** Gives a waitlisted user the namespace named by their handle, as its owner, and makes them active. The last statement changes one row when it worked. */ export function activateUser(db: D1Database, userId: string, at: number): D1PreparedStatement[] { const namespaceId = crypto.randomUUID(); return [ db.prepare("INSERT INTO namespaces (id, slug, name, kind, created_at) SELECT ?, handle, handle, 'user', ? FROM users WHERE id = ? AND status = 'waitlisted' AND handle IS NOT NULL").bind(namespaceId, at, userId), db.prepare("INSERT INTO memberships (namespace_id, user_id, role, created_at) SELECT ?, id, 'owner', ? FROM users WHERE id = ? AND status = 'waitlisted'").bind(namespaceId, at, userId), db.prepare("UPDATE users SET status = 'active' WHERE id = ? AND status = 'waitlisted'").bind(userId), ]; } export function descriptionError(description: string): string | undefined { if (description.length > MAX_DESCRIPTION_LENGTH) return "Description is too long."; } export function importUrlError(url: string): string | undefined { try { const parsed = new URL(url); if (parsed.protocol !== "https:" || parsed.username || parsed.password) return "Use a public HTTPS URL without credentials."; } catch { return "Enter a valid HTTPS URL."; } } export interface ProvisionInput { name: string; description: string; visibility: Visibility; forkOf?: string; importUrl?: string; } /** Reserves the name in D1, then creates the Artifacts repository; rolls the row back if Artifacts fails. */ export async function provisionRepo(db: D1Database, actor: Actor, namespaceId: string, input: ProvisionInput, provision: (id: string) => Promise): Promise<{ id: string } | { error: string; conflict: boolean }> { const creator = principal(actor); if (!creator) return { error: "Sign in to create repositories.", conflict: false }; const id = crypto.randomUUID(); try { await db .prepare( "INSERT INTO repos (id, namespace_id, name, description, visibility, artifacts_name, creator_id, forked_from_repo_id, forked_from_url, created_at, tips_checked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ) .bind(id, namespaceId, input.name, input.description, input.visibility, id, creator.id, input.forkOf ?? null, input.importUrl ?? null, now(), input.forkOf || input.importUrl ? null : now()) .run(); } catch { return { error: `A repository named "${input.name}" already exists.`, conflict: true }; } try { await provision(id); } catch (error) { console.error("artifacts provisioning failed", id, error); await db.prepare("DELETE FROM repos WHERE id = ?").bind(id).run(); return { error: input.importUrl ? "Couldn't import from that URL. Make sure it's a public Git repository." : "Couldn't create the repository storage. Try again.", conflict: false }; } return { id }; }