import {z} from 'zod' export type GetApiV1WebhooksOptions = {baseUrl: string, TokenBasic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const webhook = z.object({id: z.string().optional(), url: z.string(), description: z.string().nullable().optional(), enabled_events: z.array(z.enum(["all", "shipment_purchased", "shipment_cancelled", "shipment_fulfilled", "shipment_out_for_delivery", "shipment_needs_attention", "shipment_delivery_failed", "tracker_created", "tracker_updated", "order_created", "order_updated", "order_fulfilled", "order_cancelled", "order_delivered", "batch_queued", "batch_failed", "batch_running", "batch_completed"])), disabled: z.boolean().nullable().optional(), object_type: z.string().optional(), last_event_at: z.string().nullable().optional(), secret: z.string(), test_mode: z.boolean()}); export const webhookList = z.object({count: z.number().int().nullable().optional(), next: z.string().nullable().optional(), previous: z.string().nullable().optional(), results: z.array(webhook)}); 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 }; /** * List all webhooks * * GET /v1/webhooks * * Also accepts auth: Token, OAuth2, JWT */ export const getApiV1Webhooks = async (options: GetApiV1WebhooksOptions) => { const {baseUrl, fetch: fetchFn = fetch, TokenBasic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (TokenBasic !== undefined) headers.set('authorization', `Basic ${btoa(`${TokenBasic.username}:${TokenBasic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/webhooks${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(webhookList, await res.json()) };