import {z} from 'zod' export type CreateApiMatrixClientV3SearchArgs = {next_batch?: string | undefined, body: {search_categories: {room_events?: ({event_context?: ({after_limit?: number | undefined, before_limit?: number | undefined, include_profile?: boolean | undefined}) | undefined, filter?: ({limit?: number | undefined, not_senders?: Array | undefined, not_types?: Array | undefined, senders?: Array | undefined, types?: Array | undefined, contains_url?: boolean | undefined, include_redundant_members?: boolean | undefined, lazy_load_members?: boolean | undefined, not_rooms?: Array | undefined, rooms?: Array | undefined, unread_thread_notifications?: boolean | undefined}) | undefined, groupings?: ({group_by?: (Array<{key?: ('room_id' | 'sender') | undefined}>) | undefined}) | undefined, include_state?: boolean | undefined, keys?: (Array<'content.body' | 'content.name' | 'content.topic'>) | undefined, order_by?: ('recent' | 'rank') | undefined, search_term: string}) | undefined}}}; export type CreateApiMatrixClientV3SearchOptions = {baseUrl?: string | undefined, accessTokenQuery?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiMatrixClientV3SearchResponse = z.object({search_categories: z.object({room_events: z.object({count: z.number().int().optional(), groups: z.record(z.string(), z.record(z.string(), z.object({next_batch: z.string().optional(), order: z.number().int().optional(), results: z.array(z.string()).optional()}))).optional(), highlights: z.array(z.string()).optional(), next_batch: z.string().optional(), results: z.array(z.object({context: z.object({end: z.string().optional(), events_after: z.array(z.object({content: z.object({}), event_id: z.string(), origin_server_ts: z.number().int(), sender: z.string(), state_key: z.string().optional(), type: z.string(), unsigned: z.object({age: z.number().int().optional(), membership: z.string().optional(), prev_content: z.object({}).optional(), redacted_because: z.object({}).optional(), replaces_state: z.string().optional(), transaction_id: z.string().optional()}).optional(), room_id: z.string()})).optional(), events_before: z.array(z.object({content: z.object({}), event_id: z.string(), origin_server_ts: z.number().int(), sender: z.string(), state_key: z.string().optional(), type: z.string(), unsigned: z.object({age: z.number().int().optional(), membership: z.string().optional(), prev_content: z.object({}).optional(), redacted_because: z.object({}).optional(), replaces_state: z.string().optional(), transaction_id: z.string().optional()}).optional(), room_id: z.string()})).optional(), profile_info: z.object({}).optional(), start: z.string().optional()}).optional(), rank: z.number().optional(), result: z.object({content: z.object({}), event_id: z.string(), origin_server_ts: z.number().int(), sender: z.string(), state_key: z.string().optional(), type: z.string(), unsigned: z.object({age: z.number().int().optional(), membership: z.string().optional(), prev_content: z.object({}).optional(), redacted_because: z.object({}).optional(), replaces_state: z.string().optional(), transaction_id: z.string().optional()}).optional(), room_id: z.string()}).optional()})).optional(), state: z.object({}).optional()}).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 }; /** * Perform a server-side search. * * POST /_matrix/client/v3/search * * Also accepts auth: accessTokenBearer */ export const createApiMatrixClientV3Search = async (args: CreateApiMatrixClientV3SearchArgs, options?: CreateApiMatrixClientV3SearchOptions) => { 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 (args.next_batch != null) query.append("next_batch", String(args.next_batch)) if (accessTokenQuery !== undefined) query.set("access_token", accessTokenQuery) const url = `${baseUrl.replace(/\/+$/, '')}/_matrix/client/v3/search${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(createApiMatrixClientV3SearchResponse, await res.json()) };