import { ok } from "@atcute/client"; import type { Cid, Datetime, Did, Nsid } from "@atcute/lexicons/syntax"; import { recordKeyOf } from "$lib/api/syntax"; import type { OAuthUserAgent } from "@atcute/oauth-browser-client"; import { awaitIndexedRecord } from "$lib/api/awaitRecord"; import { serviceUrlFor } from "$lib/api/_request"; import { createBobbinClient, type BobbinContext } from "$lib/api/client"; import { DEFAULT_LABELS } from "$lib/api/labels"; import { mainSchema as createRepoSchema } from "$lib/api/lexicons/types/sh/tangled/repo/create"; import { mainSchema as deleteRepoSchema } from "$lib/api/lexicons/types/sh/tangled/repo/delete"; import type { RepoRecord } from "$lib/api/records"; import { createRecord, deleteRecord, putRecord, type WrittenRecord } from "$lib/api/write"; import { pingIndexNow } from "$lib/api/indexnow"; const REPO_COLLECTION = "sh.tangled.repo" as Nsid; export interface RepoCreationInput { ownerDid: Did; ownerHandle: string; name: string; description?: string; defaultBranch?: string; knot: string; spindle?: string; source?: { record: string; cloneUrl: string; }; } export interface CreatedRepo { ownerHandle: string; name: string; repoDid: Did; } export const validateRepoName = (rawName: string): string => { if (rawName.length === 0) throw new Error("Repository name cannot be empty."); if (rawName.length > 100) throw new Error("Repository name must be 100 characters or fewer."); if (rawName.includes("/") || rawName.includes("\\")) { throw new Error("Repository name contains invalid path characters."); } if (rawName.startsWith(".") || rawName.endsWith(".")) { throw new Error("Repository name contains an invalid path sequence."); } if (!/^[a-zA-Z0-9._-]+$/.test(rawName)) { throw new Error( "Repository name can only contain alphanumeric characters, periods, hyphens, and underscores." ); } if (rawName.includes("..")) throw new Error("Repository name cannot contain sequential dots."); if (rawName.toLowerCase() === "self") throw new Error(`Repository name ${JSON.stringify(rawName)} is reserved.`); return rawName.endsWith(".git") ? rawName.slice(0, -4) : rawName; }; const messageOf = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause); const sleep = (milliseconds: number): Promise => { const { promise, resolve } = Promise.withResolvers(); setTimeout(resolve, milliseconds); return promise; }; const deleteOptimisticRecord = async ( agent: OAuthUserAgent, rkey: string, cid: Cid ): Promise => { try { await deleteRecord(agent, REPO_COLLECTION, rkey, cid); return null; } catch (cause) { return `the repository record could not be reverted: ${messageOf(cause)}`; } }; const deleteKnotRepo = async ( agent: OAuthUserAgent, input: RepoCreationInput, rkey: string, repoDid: Did ): Promise => { const ctx = createBobbinClient({ serviceUrl: serviceUrlFor(input.knot), agent }); let lastError = "unknown error"; for (const delay of [0, 2_000, 5_000]) { if (delay > 0) await sleep(delay); try { await ok( ctx.xrpc.call(deleteRepoSchema, { input: { repo: repoDid, did: input.ownerDid, name: rkey, rkey: recordKeyOf(rkey) } }) ); return null; } catch (cause) { lastError = messageOf(cause); } } return `the repository on ${input.knot} could not be reverted: ${lastError}`; }; const completeCreation = async ( agent: OAuthUserAgent, bobbin: BobbinContext, input: RepoCreationInput, rkey: string, record: RepoRecord, initial: WrittenRecord ): Promise<{ repoDid: Did }> => { let repoDid: Did | undefined; let currentCid = initial.cid; try { const knot = createBobbinClient({ serviceUrl: serviceUrlFor(input.knot), agent }); const created = await ok( knot.xrpc.call(createRepoSchema, { input: { rkey: recordKeyOf(rkey), name: rkey, ...(input.defaultBranch ? { defaultBranch: input.defaultBranch } : {}), ...(input.source ? { source: input.source.cloneUrl } : {}) } }) ); repoDid = created.repoDid; if (!repoDid) { throw new Error("Knot failed to mint a repo DID. The knot may need to be upgraded."); } const committed = await putRecord( agent, REPO_COLLECTION, rkey, { ...record, repoDid }, initial.cid ); currentCid = committed.cid; await awaitIndexedRecord(bobbin, committed); return { repoDid }; } catch (cause) { const recordRollback = await deleteOptimisticRecord(agent, rkey, currentCid); const knotRollback = repoDid && !recordRollback ? await deleteKnotRepo(agent, input, rkey, repoDid) : null; const rollback = [recordRollback, knotRollback].filter(Boolean).join("; "); throw new Error( `Failed to create repository: ${messageOf(cause)}${rollback ? `. Also, ${rollback}.` : ""}`, { cause } ); } }; // announce first so bobbin observes each side of the transaction in order export const createRepo = async ( agent: OAuthUserAgent, bobbinUrl: string, input: RepoCreationInput ): Promise => { const name = validateRepoName(input.name); const rkey = name.toLowerCase(); const description = input.description?.trim() || undefined; const spindle = input.spindle?.trim() || undefined; if ([...(description ?? "")].length > 140) { throw new Error("Description must be 140 characters or fewer."); } if (!input.knot) throw new Error("Select a knot."); if (agent.sub !== input.ownerDid) throw new Error("The active account changed. Try again."); const record: RepoRecord = { $type: "sh.tangled.repo", knot: input.knot, createdAt: new Date().toISOString() as Datetime, labels: DEFAULT_LABELS, ...(name !== rkey ? { name } : {}), ...(description ? { description } : {}), ...(spindle ? { spindle } : {}), ...(input.source ? { source: input.source.record as never } : {}) }; const bobbin = createBobbinClient({ serviceUrl: bobbinUrl }); const initial = await createRecord(agent, REPO_COLLECTION, record, rkey); try { await awaitIndexedRecord(bobbin, initial); } catch (cause) { const rollback = await deleteOptimisticRecord(agent, rkey, initial.cid); throw new Error( `Failed to announce repository creation: ${messageOf(cause)}${rollback ? `. Also, ${rollback}.` : ""}`, { cause } ); } const { repoDid } = await completeCreation(agent, bobbin, input, rkey, record, initial); pingIndexNow(`https://tangled.org/${input.ownerHandle}/${name}`); return { ownerHandle: input.ownerHandle, name, repoDid }; };