import {z} from 'zod' export type BasicAuthAuthentication = {type: 'basic_auth', data?: ({username: string, password?: string | undefined}) | undefined}; export type BearerTokenAuthentication = {type: 'bearer_token', data?: ({token?: string | undefined}) | undefined}; export type ApiKeyAuthentication = {type: 'api_key', data?: ({name: string, value?: string | undefined}) | undefined, add_position: 'header' | 'query_string'}; export type WebhookTestRequest = {webhook: {endpoint: string, http_method?: ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE') | undefined, request_format?: ('json' | 'xml' | 'form_encoded') | undefined, authentication?: (BasicAuthAuthentication | BearerTokenAuthentication | ApiKeyAuthentication) | undefined, custom_headers?: {[key: string]: string} | undefined}}; export type CreateApiApiV2WebhooksTestArgs = {webhook_id?: string | undefined, body: WebhookTestRequest}; export type CreateApiApiV2WebhooksTestOptions = {baseUrl?: string | undefined, apiTokenAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const webhookTestResponse = z.object({test: z.object({status: z.string().optional(), message: z.string().optional(), response_code: z.number().int().optional(), response_body: z.string().optional()}).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 }; /** * Test Webhook * * POST /api/v2/webhooks/test */ export const createApiApiV2WebhooksTest = async (args: CreateApiApiV2WebhooksTestArgs, options?: CreateApiApiV2WebhooksTestOptions) => { const {baseUrl = "https://example.zendesk.com", fetch: fetchFn = fetch, apiTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.webhook_id != null) query.append("webhook_id", String(args.webhook_id)) if (apiTokenAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${apiTokenAuth.username}:${apiTokenAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/webhooks/test${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(webhookTestResponse, await res.json()) };