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 WebhookSigningSecret = {algorithm?: string | undefined, secret?: string | undefined}; export type Webhook = {id?: string | undefined, name: string, description?: string | undefined, endpoint: string, http_method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', request_format: 'json' | 'xml' | 'form_encoded', status: 'active' | 'inactive', subscriptions?: Array | undefined, authentication?: (BasicAuthAuthentication | BearerTokenAuthentication | ApiKeyAuthentication) | undefined, custom_headers?: {[key: string]: string} | undefined, signing_secret?: WebhookSigningSecret | undefined, external_source?: ({name?: string | undefined, version?: string | undefined}) | undefined, created_at?: string | undefined, created_by?: string | undefined, updated_at?: string | undefined, updated_by?: string | undefined}; export type WebhookCreateRequest = {webhook: Webhook}; export type CreateApiApiV2WebhooksArgs = {clone_webhook_id?: string | undefined, body: WebhookCreateRequest}; export type CreateApiApiV2WebhooksOptions = {baseUrl?: string | undefined, apiTokenAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const basicAuthAuthentication = z.object({type: z.literal("basic_auth"), data: z.object({username: z.string(), password: z.string().optional()}).optional()}); export const bearerTokenAuthentication = z.object({type: z.literal("bearer_token"), data: z.object({token: z.string().optional()}).optional()}); export const apiKeyAuthentication = z.object({type: z.literal("api_key"), data: z.object({name: z.string(), value: z.string().optional()}).optional(), add_position: z.enum(["header", "query_string"])}); export const webhookSigningSecret = z.object({algorithm: z.string().optional(), secret: z.string().optional()}); export const webhook = z.object({id: z.string().optional(), name: z.string(), description: z.string().optional(), endpoint: z.string(), http_method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), request_format: z.enum(["json", "xml", "form_encoded"]), status: z.enum(["active", "inactive"]), subscriptions: z.array(z.string()).optional(), authentication: z.union([basicAuthAuthentication, bearerTokenAuthentication, apiKeyAuthentication]).optional(), custom_headers: z.record(z.string(), z.string()).optional(), signing_secret: webhookSigningSecret.optional(), external_source: z.object({name: z.string().optional(), version: z.string().optional()}).optional(), created_at: z.string().optional(), created_by: z.string().optional(), updated_at: z.string().optional(), updated_by: z.string().optional()}); export const webhookResponse = z.object({webhook: webhook.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 or Clone Webhook * * POST /api/v2/webhooks */ export const createApiApiV2Webhooks = async (args: CreateApiApiV2WebhooksArgs, options?: CreateApiApiV2WebhooksOptions) => { 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.clone_webhook_id != null) query.append("clone_webhook_id", String(args.clone_webhook_id)) if (apiTokenAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${apiTokenAuth.username}:${apiTokenAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/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(webhookResponse, await res.json()) };