import { ClientResponseError, ok } from "@atcute/client"; import { mainSchema as describeServerSchema } from "@atcute/atproto/types/server/describeServer"; import { mainSchema as updateHandleSchema } from "@atcute/atproto/types/identity/updateHandle"; import type { Handle } from "@atcute/lexicons/syntax"; import type { OAuthUserAgent } from "@atcute/oauth-browser-client"; import { createClient } from "#lib/auth/agent.ts"; import type { Permission } from "#lib/auth/scopes.ts"; import { clear } from "#lib/api/cache.ts"; import { sentence } from "#lib/format.ts"; export const HANDLE_PERMISSION: Permission = { resource: "identity", attr: "handle" }; export const handleDomains = async (agent: OAuthUserAgent): Promise => { const { availableUserDomains } = await ok(createClient(agent).call(describeServerSchema, {})); return availableUserDomains; }; const updateHandleError = (cause: ClientResponseError): string => { if (cause.error === "HandleNotAvailable") return "This handle is taken. Choose another one."; if (cause.error === "InvalidHandle") return "This handle isn't allowed. Choose another one."; if (cause.description) return sentence(cause.description); return "Could not change your handle. Try again."; }; export const updateHandle = async (agent: OAuthUserAgent, handle: Handle): Promise => { try { await ok(createClient(agent).call(updateHandleSchema, { input: { handle } })); } catch (cause) { if (cause instanceof ClientResponseError) { throw new Error(updateHandleError(cause), { cause }); } throw cause; } clear(); };