import {z} from 'zod' export type GetApiV3MetricsSendSummaryArgs = {start?: string | undefined, end?: string | undefined, sending_domain?: string | undefined}; export type GetApiV3MetricsSendSummaryOptions = {baseUrl?: string | undefined, NYLASAPIKEY?: string | undefined, fetch?: typeof fetch | undefined}; export const window = z.object({start: z.string().optional(), end: z.string().optional()}); export const counts = z.object({sent: z.number().int().optional(), delivered: z.number().int().optional(), bounced_hard: z.number().int().optional(), bounced_soft: z.number().int().optional(), bounced_undetermined: z.number().int().optional(), rejected: z.number().int().optional(), complaints: z.number().int().optional()}); export const sendFinding = z.object({rule: z.enum(["concentration", "spike", "overall"]).optional(), severity: z.enum(["high", "watch"]).optional(), title: z.string().optional(), evidence: z.object({metric: z.enum(["delivery_rate", "bounce_rate", "complaint_rate"]).optional(), value: z.number().optional(), threshold: z.number().optional(), dimension: z.enum(["sending_domain", "agent_account", "recipient_domain", ""]).optional(), dimension_value: z.string().optional(), share_of_excess: z.number().optional(), day: z.string().optional(), baseline_value: z.number().optional(), totals: counts.optional(), window: window.optional()}).optional(), recommendation: z.string().optional(), logs_filter: z.record(z.string(), z.unknown()).optional()}); export const sendSummary = z.object({health: z.object({state: z.enum(["healthy", "at_risk", "critical", "insufficient_data"]).optional(), window: window.optional(), min_assess_volume: z.number().int().optional(), findings: z.array(sendFinding).optional()}).optional(), totals: counts.optional(), metrics: z.object({delivery_rate: z.object({value: z.number().nullable().optional(), delta_pp: z.number().nullable().optional(), prior_value: z.number().nullable().optional(), status: z.enum(["ok", "warn", "crit", "null"]).nullable().optional()}).optional(), bounce_rate: z.object({value: z.number().nullable().optional(), delta_pp: z.number().nullable().optional(), prior_value: z.number().nullable().optional(), status: z.enum(["ok", "warn", "crit", "null"]).nullable().optional()}).optional(), complaint_rate: z.object({value: z.number().nullable().optional(), delta_pp: z.number().nullable().optional(), prior_value: z.number().nullable().optional(), status: z.enum(["ok", "warn", "crit", "null"]).nullable().optional()}).optional()}).optional(), prior_period: window.nullable().optional()}); export const getApiV3MetricsSendSummaryResponse = z.object({request_id: z.string().optional(), data: sendSummary.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 }; /** * Return a sending health summary * * GET /v3/metrics/send/summary */ export const getApiV3MetricsSendSummary = async (args: GetApiV3MetricsSendSummaryArgs, options?: GetApiV3MetricsSendSummaryOptions) => { const {baseUrl = "https://api.us.nylas.com", fetch: fetchFn = fetch, NYLASAPIKEY} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start != null) query.append("start", String(args.start)) if (args.end != null) query.append("end", String(args.end)) if (args.sending_domain != null) query.append("sending_domain", String(args.sending_domain)) if (NYLASAPIKEY !== undefined) headers.set('authorization', `Bearer ${NYLASAPIKEY}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/metrics/send/summary${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(getApiV3MetricsSendSummaryResponse, await res.json()) };