import {z} from 'zod' export type GetApiV2ReportingMetricsIdResultsArgs = {id: string}; export type GetApiV2ReportingMetricsIdResultsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const metricCalculationMetadata = z.object({template: z.enum(["GROSS_VOLUME", "TRANSACTION_COUNT", "NEW_USERS"]).optional(), recordCount: z.number().int().optional(), projectedRowCount: z.number().int().nullable().optional(), filledCount: z.number().int().optional(), calculationInterval: z.enum(["day", "week", "month", "quarter", "year"]).optional(), dateRange: z.object({start: z.string().optional(), end: z.string().optional()}).optional(), filters: z.record(z.string(), z.unknown()).optional(), breakdowns: z.object({dimensions: z.array(z.enum(["transactionType", "transactionStatus", "userId"])).optional(), dimensionCounts: z.record(z.string(), z.number().int()).optional()}).nullable().optional(), metric: z.string().nullable().optional()}); export const metricCalculationResponse = z.object({status: z.literal("success").optional(), data: z.array(z.object({periodStart: z.string().optional(), grossVolume: z.number().optional(), grossVolumeUsd: z.number().optional(), transactionCount: z.number().optional(), newUserCount: z.number().optional(), transactionType: z.enum(["onramp", "offramp", "transfer"]).optional(), transactionStatus: z.enum(["AWAITING_FUNDS", "COMPLETED", "CRYPTO_FAILED", "CRYPTO_INITIATED", "CRYPTO_PENDING", "FAILED", "FIAT_FAILED", "FIAT_INITIATED", "FIAT_PENDING", "FIAT_PROCESSED", "FIAT_RETURNED", "INITIATED", "NOT_INITIATED", "PENDING", "QUOTE_FAILED", "REJECTED"]).optional(), userId: z.string().optional()}).and(z.record(z.string(), z.unknown()))).optional(), metadata: metricCalculationMetadata.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 }; /** * Execute Saved Metric * * GET /v2/reporting/metrics/{id}/results */ export const getApiV2ReportingMetricsIdResults = async (args: GetApiV2ReportingMetricsIdResultsArgs, options?: GetApiV2ReportingMetricsIdResultsOptions) => { const {baseUrl = "https://production.hifibridge.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/reporting/metrics/${encodeURIComponent(String(args.id))}/results${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(metricCalculationResponse, await res.json()) };