import {z} from 'zod' export type GetApiWebhooksArgs = {page?: number | undefined, page_size?: number | undefined}; export type GetApiWebhooksOptions = {baseUrl?: string | undefined, AccessTokenAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const pagination = z.object({num_pages: z.number().int(), page: z.number().int(), page_size: z.number().int(), total: z.number().int()}); export const webhook = z.object({account_id: z.string(), created_at: z.string(), created_by_id: z.string(), deleted_at: z.string().optional(), last_checked_at: z.string().nullable(), name: z.string(), state: z.enum(["healthy", "unhealthy", "unknown"]), url: z.string()}); export const listWebhooksResponse = z.object({$schema: z.string().optional(), pages: pagination, webhooks: z.array(webhook)}); 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 }; /** * List webhooks * * GET /webhooks * * Also accepts auth: APIKeyAuth */ export const getApiWebhooks = async (args: GetApiWebhooksArgs, options?: GetApiWebhooksOptions) => { const {baseUrl = "https://api.tower.dev/v1", fetch: fetchFn = fetch, AccessTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.page_size != null) query.append("page_size", String(args.page_size)) if (AccessTokenAuth !== undefined) headers.set('authorization', `Bearer ${AccessTokenAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/webhooks${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(listWebhooksResponse, await res.json()) };