import {z} from 'zod' export type CreateApiMatrixClientV3LoginArgs = {body: {address?: string | undefined, device_id?: string | undefined, identifier?: ({type: string} | {[key: string]: unknown}) | undefined, initial_device_display_name?: string | undefined, medium?: string | undefined, password?: string | undefined, refresh_token?: boolean | undefined, token?: string | undefined, type: string, user?: string | undefined}}; export type CreateApiMatrixClientV3LoginOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiMatrixClientV3LoginResponse = z.object({access_token: z.string(), device_id: z.string(), expires_in_ms: z.number().int().optional(), home_server: z.string().optional(), refresh_token: z.string().optional(), user_id: z.string(), well_known: z.object({"m.homeserver": z.object({base_url: z.string()}), "m.identity_server": z.object({base_url: z.string()}).optional()}).and(z.record(z.string(), z.unknown())).optional()}); 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 }; /** * Authenticates the user. * * POST /_matrix/client/v3/login */ export const createApiMatrixClientV3Login = async (args: CreateApiMatrixClientV3LoginArgs, options?: CreateApiMatrixClientV3LoginOptions) => { const {baseUrl = "https://matrix.org", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/_matrix/client/v3/login${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiMatrixClientV3LoginResponse, await res.json()) };