import {z} from 'zod' export type CreateApiMatrixClientV3CreateRoomArgs = {body: {creation_content?: Record | undefined, initial_state?: (Array<{content: Record, state_key?: string | undefined, type: string}>) | undefined, invite?: Array | undefined, invite_3pid?: Array<{address: string, id_access_token: string, id_server: string, medium: string}> | undefined, is_direct?: boolean | undefined, name?: string | undefined, power_level_content_override?: Record | undefined, preset?: ('private_chat' | 'public_chat' | 'trusted_private_chat') | undefined, room_alias_name?: string | undefined, room_version?: string | undefined, topic?: string | undefined, visibility?: ('public' | 'private') | undefined}}; export type CreateApiMatrixClientV3CreateRoomOptions = {baseUrl?: string | undefined, accessTokenQuery?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiMatrixClientV3CreateRoomResponse = z.object({room_id: z.string()}); 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 }; /** * Create a new room * * POST /_matrix/client/v3/createRoom * * Also accepts auth: accessTokenBearer */ export const createApiMatrixClientV3CreateRoom = async (args: CreateApiMatrixClientV3CreateRoomArgs, options?: CreateApiMatrixClientV3CreateRoomOptions) => { const {baseUrl = "https://matrix.org", fetch: fetchFn = fetch, accessTokenQuery} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (accessTokenQuery !== undefined) query.set("access_token", accessTokenQuery) const url = `${baseUrl.replace(/\/+$/, '')}/_matrix/client/v3/createRoom${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(createApiMatrixClientV3CreateRoomResponse, await res.json()) };