import {z} from 'zod' export type MeteringEvent = {transactionId: string, payload: string, sourceId?: string | undefined, subscriberCredentialId?: string | undefined, sourceType: 'UNKNOWN' | 'AI' | 'SDK_PYTHON' | 'SDK_JS' | 'SDK_JVM' | 'SDK_SPRING' | 'SDK_DOTNET' | 'SDK_GOLANG' | 'SDK_RUST' | 'EBPF' | 'AWS' | 'AZURE' | 'SNOWFLAKE' | 'KONG' | 'GRAVITEE' | 'MULESOFT' | 'BOOMI' | 'REVENIUM' | 'INTERNAL'}; export type CreateApiV2EventsArgs = {body: MeteringEvent}; export type CreateApiV2EventsOptions = {baseUrl?: string | undefined, xApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const link = z.object({href: z.string().optional(), hreflang: z.string().optional(), title: z.string().optional(), type: z.string().optional(), deprecation: z.string().optional(), profile: z.string().optional(), name: z.string().optional(), templated: z.boolean().optional()}); export const links = z.record(z.string(), link); export const meteringResponseResource = z.object({object: z.string(), label: z.string(), created: z.string().optional(), updated: z.string().optional(), id: z.string(), signature: z.string(), _links: links.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 }; /** * Meter an event * * POST /v2/events */ export const createApiV2Events = async (args: CreateApiV2EventsArgs, options?: CreateApiV2EventsOptions) => { const {baseUrl = "https://api.revenium.io/meter", fetch: fetchFn = fetch, xApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (xApiKey !== undefined) headers.set("x-api-key", xApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/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(meteringResponseResource, await res.json()) };