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 { hostForKnot, 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, readRecord, type WrittenRecord } from "$lib/api/write"; import { pingIndexNow } from "$lib/api/indexnow"; const REPO_COLLECTION = "sh.tangled.repo" as Nsid; type RepoCreationSource = { kind: "fork"; url: string; record: string } | { kind: "import"; url: string }; export interface RepoCreationInput { ownerDid: Did; ownerHandle: string; name: string; description?: string; defaultBranch?: string; knot: string; spindle?: string; source?: RepoCreationSource; } 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 /\.git$/i.test(rawName) ? 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 knotHost = hostForKnot(input.knot); const ctx = createBobbinClient({ serviceUrl: serviceUrlFor(knotHost), 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 ${knotHost} 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(record.knot), agent }); const created = await ok( knot.xrpc.call(createRepoSchema, { input: { rkey: recordKeyOf(rkey), name: rkey, ...(input.defaultBranch ? { defaultBranch: input.defaultBranch } : {}), ...(input.source ? { source: { url: input.source.url as never, kind: input.source.kind } } : {}) } }) ); 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 } ); } }; interface OptimisticRepoRecord { rkey: string; name: string; record: RepoRecord; initial: WrittenRecord; bobbin: BobbinContext; } // announce first so bobbin observes each side of the transaction in order export const createOptimisticRepoRecord = 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 knot = hostForKnot(input.knot); const record: RepoRecord = { $type: "sh.tangled.repo", knot, createdAt: new Date().toISOString() as Datetime, labels: DEFAULT_LABELS, ...(name !== rkey ? { name } : {}), ...(description ? { description } : {}), ...(spindle ? { spindle } : {}), ...(input.source?.kind === "fork" ? { source: input.source.record as never } : {}) }; // records without repoDid are interrupted optimistic creates on this knot, resume to avoid stranding rkey const existing = await readRecord(agent, REPO_COLLECTION, rkey); const resuming = existing !== null && !existing.value.repoDid && existing.value.knot === knot ? existing : null; if (existing && !resuming) throw new Error( `A repository named "${name}" already exists in your account. Choose another name.` ); const bobbin = createBobbinClient({ serviceUrl: bobbinUrl }); const initial = resuming ? await putRecord(agent, REPO_COLLECTION, rkey, record, resuming.written?.cid) : 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 } ); } return { rkey, name, record, initial, bobbin }; }; export const createRepo = async ( agent: OAuthUserAgent, bobbinUrl: string, input: RepoCreationInput ): Promise => { const { rkey, name, record, initial, bobbin } = await createOptimisticRepoRecord( agent, bobbinUrl, input ); const { repoDid } = await completeCreation(agent, bobbin, input, rkey, record, initial); pingIndexNow(`https://tangled.org/${input.ownerHandle}/${name}`); return { ownerHandle: input.ownerHandle, name, repoDid }; };