167 lines · 7.9 KBRaw
| 1 | import { now } from "./auth.ts"; |
| 2 | import type { Actor, Role } from "./contract/actor.ts"; |
| 3 | import { MAX_DESCRIPTION_LENGTH } from "./contract/limits.ts"; |
| 4 | import type { RepoSummary, Visibility } from "./contract/views.ts"; |
| 5 | import { Policy, principal, type RepoFacts } from "./policy.ts"; |
| 6 | |
| 7 | export interface Namespace { |
| 8 | id: string; |
| 9 | slug: string; |
| 10 | name: string; |
| 11 | kind: "user" | "org"; |
| 12 | } |
| 13 | |
| 14 | export interface RepoRecord { |
| 15 | id: string; |
| 16 | namespace_id: string; |
| 17 | name: string; |
| 18 | full_name: string; |
| 19 | description: string; |
| 20 | visibility: Visibility; |
| 21 | default_branch: string; |
| 22 | artifacts_name: string; |
| 23 | creator_id: string; |
| 24 | created_at: number; |
| 25 | forked_from_url: string | null; |
| 26 | forked_from_name: string | null; |
| 27 | open_tasks: number; |
| 28 | open_pulls: number; |
| 29 | forks: number; |
| 30 | } |
| 31 | |
| 32 | const REPO_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; |
| 33 | const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/; |
| 34 | const RESERVED_SLUGS = new Set(["organizations", "switch", "new", "setup", "login", "logout", "signup", "waitlist", "forgot-password", "reset-password", "invite", "settings", "tasks", "assets", "api", "mcp", "oauth", "install", "cli", "admin", "docs"]); |
| 35 | |
| 36 | const SELECT_REPO = |
| 37 | "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"; |
| 38 | |
| 39 | export function repoFacts(record: RepoRecord): RepoFacts { |
| 40 | return { name: record.full_name, visibility: record.visibility, creatorId: record.creator_id }; |
| 41 | } |
| 42 | |
| 43 | export async function namespaceBySlug(db: D1Database, slug: string): Promise<Namespace | null> { |
| 44 | return db.prepare("SELECT id, slug, name, kind FROM namespaces WHERE slug = ?").bind(slug).first<Namespace>(); |
| 45 | } |
| 46 | |
| 47 | /** Every namespace the actor's human belongs to: their own account first, then organizations by name. */ |
| 48 | export async function memberNamespaces(db: D1Database, actor: Actor): Promise<Namespace[]> { |
| 49 | const person = principal(actor); |
| 50 | if (!person) return []; |
| 51 | const { results } = await db |
| 52 | .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") |
| 53 | .bind(person.id) |
| 54 | .all<Namespace>(); |
| 55 | return results; |
| 56 | } |
| 57 | |
| 58 | export async function namespacePolicy(db: D1Database, base: Policy, namespaceId: string): Promise<Policy> { |
| 59 | const found = await db |
| 60 | .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 = ?") |
| 61 | .bind(base.person?.id ?? null, namespaceId) |
| 62 | .first<{ kind: Namespace["kind"]; role: Role | null }>(); |
| 63 | return base.withRole(found?.role ?? null, found?.kind === "user"); |
| 64 | } |
| 65 | |
| 66 | export function splitFullName(fullName: string): { slug: string; name: string } | null { |
| 67 | const [slug, name, ...rest] = fullName.split("/"); |
| 68 | return slug && name && !rest.length ? { slug, name } : null; |
| 69 | } |
| 70 | |
| 71 | export async function findRepoRecord(db: D1Database, fullName: string): Promise<RepoRecord | null> { |
| 72 | const parts = splitFullName(fullName); |
| 73 | if (!parts) return null; |
| 74 | return db.prepare(`${SELECT_REPO} WHERE n.slug = ? AND r.name = ?`).bind(parts.slug, parts.name).first<RepoRecord>(); |
| 75 | } |
| 76 | |
| 77 | export async function findRepoRecordById(db: D1Database, id: string): Promise<RepoRecord | null> { |
| 78 | return db.prepare(`${SELECT_REPO} WHERE r.id = ?`).bind(id).first<RepoRecord>(); |
| 79 | } |
| 80 | |
| 81 | export async function listRepoRecords(db: D1Database, namespaceId: string): Promise<RepoRecord[]> { |
| 82 | const { results } = await db.prepare(`${SELECT_REPO} WHERE r.namespace_id = ? ORDER BY r.name COLLATE NOCASE`).bind(namespaceId).all<RepoRecord>(); |
| 83 | return results; |
| 84 | } |
| 85 | |
| 86 | export function toSummary(record: RepoRecord, policy: Policy, origin: string): RepoSummary { |
| 87 | const facts = repoFacts(record); |
| 88 | return { |
| 89 | name: record.full_name, |
| 90 | description: record.description, |
| 91 | visibility: record.visibility, |
| 92 | createdAt: record.created_at, |
| 93 | openTasks: record.open_tasks, |
| 94 | openPulls: record.open_pulls, |
| 95 | forks: record.forks, |
| 96 | origin: record.forked_from_url ? { kind: "import", url: record.forked_from_url } : record.forked_from_name ? { kind: "fork", repo: record.forked_from_name } : null, |
| 97 | cloneUrl: `${origin}/${record.full_name}.git`, |
| 98 | can: { write: policy.canWriteRepo(facts), admin: policy.canAdminRepo(facts) }, |
| 99 | }; |
| 100 | } |
| 101 | |
| 102 | export function repoNameError(name: string): string | undefined { |
| 103 | if (!REPO_NAME_PATTERN.test(name)) return "Use 1–100 letters, numbers, '.', '-' or '_', starting with a letter or number."; |
| 104 | if (name.toLowerCase().endsWith(".git")) return "Repository names can't end in .git."; |
| 105 | } |
| 106 | |
| 107 | export function slugError(slug: string): string | undefined { |
| 108 | if (!SLUG_PATTERN.test(slug)) return "Use 1–39 lowercase letters, numbers or '-', starting and ending with a letter or number."; |
| 109 | if (RESERVED_SLUGS.has(slug)) return `"${slug}" is reserved.`; |
| 110 | } |
| 111 | |
| 112 | /** 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. */ |
| 113 | export function activateUser(db: D1Database, userId: string, at: number): D1PreparedStatement[] { |
| 114 | const namespaceId = crypto.randomUUID(); |
| 115 | return [ |
| 116 | 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), |
| 117 | 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), |
| 118 | db.prepare("UPDATE users SET status = 'active' WHERE id = ? AND status = 'waitlisted'").bind(userId), |
| 119 | ]; |
| 120 | } |
| 121 | |
| 122 | export function descriptionError(description: string): string | undefined { |
| 123 | if (description.length > MAX_DESCRIPTION_LENGTH) return "Description is too long."; |
| 124 | } |
| 125 | |
| 126 | export function importUrlError(url: string): string | undefined { |
| 127 | try { |
| 128 | const parsed = new URL(url); |
| 129 | if (parsed.protocol !== "https:" || parsed.username || parsed.password) return "Use a public HTTPS URL without credentials."; |
| 130 | } catch { |
| 131 | return "Enter a valid HTTPS URL."; |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | export interface ProvisionInput { |
| 136 | name: string; |
| 137 | description: string; |
| 138 | visibility: Visibility; |
| 139 | forkOf?: string; |
| 140 | importUrl?: string; |
| 141 | } |
| 142 | |
| 143 | /** Reserves the name in D1, then creates the Artifacts repository; rolls the row back if Artifacts fails. */ |
| 144 | export async function provisionRepo(db: D1Database, actor: Actor, namespaceId: string, input: ProvisionInput, provision: (id: string) => Promise<unknown>): Promise<{ id: string } | { error: string; conflict: boolean }> { |
| 145 | const creator = principal(actor); |
| 146 | if (!creator) return { error: "Sign in to create repositories.", conflict: false }; |
| 147 | const id = crypto.randomUUID(); |
| 148 | try { |
| 149 | await db |
| 150 | .prepare( |
| 151 | "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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 152 | ) |
| 153 | .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()) |
| 154 | .run(); |
| 155 | } catch { |
| 156 | return { error: `A repository named "${input.name}" already exists.`, conflict: true }; |
| 157 | } |
| 158 | |
| 159 | try { |
| 160 | await provision(id); |
| 161 | } catch (error) { |
| 162 | console.error("artifacts provisioning failed", id, error); |
| 163 | await db.prepare("DELETE FROM repos WHERE id = ?").bind(id).run(); |
| 164 | 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 }; |
| 165 | } |
| 166 | return { id }; |
| 167 | } |