import {z} from 'zod' export type JIRAStatusCategory = 'To Do' | 'In Progress' | 'Done' | 'No Category'; export type JIRAFilter = {epics?: Array | undefined, labels_include?: Array | undefined, labels_exclude?: Array | undefined, issue_types?: Array | undefined, priorities?: Array | undefined, projects?: Array | undefined, status_categories?: Array | undefined, unmapped?: boolean | undefined}; export type TimeZone = number; export type JIRAFilterWith = {assignees?: (Array) | undefined, reporters?: Array | undefined, commenters?: Array | undefined}; export type JIRAMetricID = 'jira-open' | 'jira-resolved' | 'jira-raised' | 'jira-acknowledged' | 'jira-acknowledged-q' | 'jira-life-time' | 'jira-life-time-below-threshold-ratio' | 'jira-lead-time' | 'jira-lead-time-below-threshold-ratio' | 'jira-acknowledge-time' | 'jira-acknowledge-time-below-threshold-ratio' | 'jira-pr-lag-time' | 'jira-backlog-time' | 'jira-resolution-rate'; export type Quantiles = Array; export type Granularity = string; export type Granularities = Array; export type JIRAMetricsRequest = {account: number, date_from: string, date_to: string, for?: Array | undefined, timezone?: TimeZone | undefined, priorities?: Array | undefined, types?: Array | undefined, labels_include?: Array | undefined, labels_exclude?: Array | undefined, exclude_inactive: boolean, epics?: Array | undefined, with?: Array | undefined, projects?: Array | undefined, metrics: Array, quantiles?: Quantiles | undefined, granularities: Granularities, group_by_jira_label?: boolean | undefined}; export type CreateApiMetricsJiraArgs = {body: JIRAMetricsRequest}; export type CreateApiMetricsJiraOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const granularity = z.string(); export const jIRAStatusCategory = z.enum(["To Do", "In Progress", "Done", "No Category"]); export const jIRAFilter = z.object({epics: z.array(z.string()).optional(), labels_include: z.array(z.string()).optional(), labels_exclude: z.array(z.string()).optional(), issue_types: z.array(z.string()).optional(), priorities: z.array(z.string()).optional(), projects: z.array(z.string()).optional(), status_categories: z.array(jIRAStatusCategory).optional(), unmapped: z.boolean().optional()}); export const jIRAFilterWith = z.object({assignees: z.array(z.string().nullable()).optional(), reporters: z.array(z.string()).optional(), commenters: z.array(z.string()).optional()}); export const timeDuration = z.string(); export const calculatedLinearMetricValues = z.object({date: z.string(), values: z.array(z.union([z.number(), timeDuration, z.object({})])), confidence_mins: z.array(z.union([z.number().nullable(), timeDuration])).optional(), confidence_maxs: z.array(z.union([z.number().nullable(), timeDuration])).optional(), confidence_scores: z.array(z.number().int().nullable()).optional()}); export const calculatedJIRAMetricValues = z.object({granularity: granularity, for: jIRAFilter.optional(), jira_label: z.string().optional(), with: jIRAFilterWith.optional(), values: z.array(calculatedLinearMetricValues)}); export const calculatedJIRAMetrics = z.array(calculatedJIRAMetricValues); 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 }; /** * Calculate metrics over JIRA issue activities. * * POST /metrics/jira * * Also accepts auth: apiKeyAuth */ export const createApiMetricsJira = async (args: CreateApiMetricsJiraArgs, options: CreateApiMetricsJiraOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/metrics/jira${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(calculatedJIRAMetrics, await res.json()) };