import {z} from 'zod' export type WebhookRequest = {listId: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12, callbackUrl: string, limit?: number | undefined, permissionMode?: (0 | 1) | undefined}; export type CreateApiV10WebhookArgs = {Authorization: string, 'Content-Type': string, body: WebhookRequest}; export type CreateApiV10WebhookOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookResponse = z.object({subscribeId: z.number().int(), teamId: z.number().int(), listId: z.number().int(), vendorId: z.number().int().optional(), callbackUrl: z.string(), limit: z.number().int().optional(), permissionMode: z.number().int().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 Webhook * * POST /v1.0/webhook */ export const createApiV10Webhook = async (args: CreateApiV10WebhookArgs, options?: CreateApiV10WebhookOptions) => { const {baseUrl = "https://api.lofty.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) const url = `${baseUrl.replace(/\/+$/, '')}/v1.0/webhook${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()) };