import {z} from 'zod' export type GetApiRtsMessagesArgs = {limit?: number | undefined, next?: string | undefined}; export type GetApiRtsMessagesOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const messageObject = z.object({id: z.number().gte(1), created_at: z.string(), title: z.string(), type: z.enum(["my_incident", "shared_incident", "arming", "trigger_action", "open_incident_verification", "verify_incident", "close_incident", "arrow_status_online", "arrow_status_offline", "camera_status_online", "camera_status_offline"]), short_message: z.string(), long_message: z.string(), is_read: z.boolean(), read_at: z.string().optional(), image: z.string().optional(), action_url: z.string().optional(), action_label: z.string().optional(), show_detail: z.boolean(), incident_sharing_url: z.string().optional()}); export const messageListResponse = z.object({count: z.number().int().gte(0), next: z.string().nullable(), previous: z.string().nullable(), results: z.array(messageObject)}); 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 }; /** * Retrieve messages * * GET /rts/messages/ * * Also accepts auth: PersonalAccessToken */ export const getApiRtsMessages = async (args: GetApiRtsMessagesArgs, options?: GetApiRtsMessagesOptions) => { const {baseUrl = "https://api.angelcam.com/v1", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.next != null) query.append("next", String(args.next)) if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/rts/messages/${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(messageListResponse, await res.json()) };