import {z} from 'zod' export type Attribute = {name: string, value: string, unit?: string | undefined}; export type Dimensions = {[key: string]: string}; export type Event = {schemaName: string, id?: string | undefined, timestamp: string, accountId: string, attributes: Array, dimensions: Dimensions}; export type EventCorrectionRequest = {event?: Event | undefined}; export type CreateApiEventsCorrectionArgs = {action: 'UNDO' | 'REDO' | 'REDO_EVENT', require_confirmation?: boolean | undefined, body: EventCorrectionRequest}; export type CreateApiEventsCorrectionOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const attribute = z.object({name: z.string().min(1).max(50), value: z.string(), unit: z.string().min(1).max(50).optional()}); export const dimensions = z.record(z.string(), z.string().min(1).max(200)); export const event = z.object({schemaName: z.string().min(1).max(50), id: z.string().max(512).optional(), timestamp: z.string(), accountId: z.string().max(512), attributes: z.array(attribute), dimensions: dimensions}); export const ingestionStatus = z.object({status: z.enum(["INGESTION_IN_PROGRESS", "INGESTION_FAILED", "INGESTION_FAILED_SCHEMA_NOT_DEFINED", "INGESTION_FAILED_ENRICHMENT_FAILED", "INGESTION_FAILED_UNITS_INVALID", "INGESTION_COMPLETED_NO_MATCHING_METERS", "INGESTION_COMPLETED_EVENT_METERED", "INGESTION_COMPLETED_EVENT_NOT_METERED", "INGESTION_FAILED_PAST_GRACE_PERIOD", "INGESTION_FAILED_ACCOUNT_NOT_FOUND", "INGESTION_FAILED_DUPLICATE_EVENT", "INGESTION_FAILED_NO_EVENT_ID", "INGESTION_FAILED_INVALID_NAMED_LICENSE_EVENT", "INGESTION_FAILED_INSUFFICIENT_CREDITS", "REVERTED", "UNKNOWN"]), statusDescription: z.string().max(250).optional()}); export const eventSource = z.object({id: z.string().max(100), type: z.string().max(100)}); export const eventCorrectionInfo = z.object({referenceId: z.string(), eventPayload: event, ingestionStatus: ingestionStatus, customerId: z.string().max(50).optional(), source: eventSource.optional(), createdAt: z.string(), status: z.enum(["REVERTED", "REVERTED_AND_REINGESTED", "FAILED"]), reason: z.string()}); export const eventsCorrectionResponse = z.object({data: z.array(eventCorrectionInfo)}); 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 }; /** * Correct an ingested event * * POST /events/correction */ export const createApiEventsCorrection = async (args: CreateApiEventsCorrectionArgs, options?: CreateApiEventsCorrectionOptions) => { const {baseUrl = "https://api.togai.com", 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 (args.action != null) query.append("action", String(args.action)) if (args.require_confirmation != null) query.append("require_confirmation", String(args.require_confirmation)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/events/correction${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(eventsCorrectionResponse, await res.json()) };