import {z} from 'zod' export type EventCreateRequest = {customerId: string, eventTypeId: string, datetime: string, idempotencyKey: string, value: number, differentiator?: string | undefined, invoiceSplitKey?: string | undefined, metadata?: {[key: string]: Record} | undefined}; export type CreateApiV1EventsArgs = {body: EventCreateRequest}; export type CreateApiV1EventsOptions = {baseUrl?: string | undefined, customHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const eventResponse = z.object({customerId: z.string().optional(), eventTypeId: z.string().optional(), datetime: z.string().optional(), idempotencyKey: z.string().optional(), value: z.number().optional(), differentiator: z.string().optional(), invoiceSplitKey: z.string().optional(), parentEventId: z.string().optional(), metadata: z.record(z.string(), z.object({})).optional()}); export const eventData = z.object({events: eventResponse.optional()}); export const eventCreateResponse = z.object({success: z.boolean().optional(), message: z.string().optional(), data: eventData.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 }; /** * Create an event * * POST /v1/events */ export const createApiV1Events = async (args: CreateApiV1EventsArgs, options?: CreateApiV1EventsOptions) => { const {baseUrl = "https://integrators.prod.api.tabsplatform.com", fetch: fetchFn = fetch, customHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (customHeader !== undefined) headers.set("Authorization", customHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/events${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(eventCreateResponse, await res.json()) };