import {z} from 'zod' export type GetApiMatrixClientV3CapabilitiesOptions = {baseUrl?: string | undefined, accessTokenQuery?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiMatrixClientV3CapabilitiesResponse = z.object({capabilities: z.object({"m.3pid_changes": z.object({enabled: z.boolean()}).optional(), "m.account_moderation": z.object({lock: z.boolean().optional(), suspend: z.boolean().optional()}).optional(), "m.change_password": z.object({enabled: z.boolean()}).optional(), "m.forget_forced_upon_leave": z.object({enabled: z.boolean()}).optional(), "m.get_login_token": z.object({enabled: z.boolean()}).optional(), "m.profile_fields": z.object({allowed: z.array(z.string()).optional(), disallowed: z.array(z.string()).optional(), enabled: z.boolean()}).optional(), "m.room_versions": z.object({available: z.record(z.string(), z.enum(["stable", "unstable"])), default: z.string()}).optional(), "m.set_avatar_url": z.object({enabled: z.boolean()}).optional(), "m.set_displayname": z.object({enabled: z.boolean()}).optional()}).and(z.record(z.string(), z.unknown()))}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Gets information about the server's capabilities. * * GET /_matrix/client/v3/capabilities * * Also accepts auth: accessTokenBearer */ export const getApiMatrixClientV3Capabilities = async (options?: GetApiMatrixClientV3CapabilitiesOptions) => { const {baseUrl = "https://matrix.org", fetch: fetchFn = fetch, accessTokenQuery} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (accessTokenQuery !== undefined) query.set("access_token", accessTokenQuery) const url = `${baseUrl.replace(/\/+$/, '')}/_matrix/client/v3/capabilities${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiMatrixClientV3CapabilitiesResponse, await res.json()) };