import {z} from 'zod' export type BasicAuth = {username: string, password: string}; export type NoAuth = Record; export type TokenAuth = {value: string}; export type WebhookAuthorization = BasicAuth | NoAuth | TokenAuth; export type MapString = {[key: string]: string}; export type IsNotOneOf5 = {field: string, values: Array}; export type IsOneOf5 = {field: string, values: Array}; export type Condition1 = IsNotOneOf5 | IsOneOf5; export type Filters1 = {strategy: string, conditions: Array}; export type MapWebhookEventTypeFilters = {[key: string]: Filters1}; export type CreateWebhookSubscriptionInput = {name: string, events?: Array | undefined, url: string, authorization: WebhookAuthorization, customHeaders: MapString, enabled?: boolean | undefined, filters?: MapWebhookEventTypeFilters | undefined}; export type CreateApiBetaWebhooksArgs = {body: CreateWebhookSubscriptionInput}; export type CreateApiBetaWebhooksOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookHeadersMapStringString = z.record(z.string(), z.string()); export const isNotOneOf5 = z.object({field: z.string(), values: z.array(z.string())}); export const isOneOf5 = z.object({field: z.string(), values: z.array(z.string())}); export const condition1 = z.union([isNotOneOf5, isOneOf5]); export const filters1 = z.object({strategy: z.string(), conditions: z.array(condition1)}); export const mapWebhookEventTypeFilters = z.record(z.string(), filters1); export const webhookSubscription = z.object({id: z.string(), name: z.string(), subscribedEvents: z.array(z.string()).optional(), url: z.string(), headers: webhookHeadersMapStringString, secretKey: z.string(), enabled: z.boolean(), createdAt: z.string(), createdBy: z.string(), updatedAt: z.string(), updatedBy: z.string(), filters: mapWebhookEventTypeFilters.optional()}); export const createWebhookSubscriptionOutput = z.object({data: webhookSubscription}); 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 Webhook Subscription * * POST /beta/webhooks */ export const createApiBetaWebhooks = async (args: CreateApiBetaWebhooksArgs, options?: CreateApiBetaWebhooksOptions) => { const {baseUrl = "https://dev.dixa.io", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/beta/webhooks${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(createWebhookSubscriptionOutput, await res.json()) };