import {z} from 'zod' export type TransportMode = 'parcel' | 'postal' | 'express' | 'road_freight' | 'air_cargo' | 'ocean_container'; export type GetApiCarriersArgs = {query?: string | undefined, transport_mode?: TransportMode | undefined, limit?: number | undefined}; export type GetApiCarriersOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const transportMode = z.enum(["parcel", "postal", "express", "road_freight", "air_cargo", "ocean_container"]); export const deliveryEstimateCarrierSearchResponse = z.object({query: z.string(), transport_mode: transportMode.nullable().optional(), carriers: z.array(z.object({slug: z.string(), name: z.string(), aliases: z.array(z.string()), transport_modes: z.array(transportMode)})), total_matches: z.number().int().gte(0), has_more: z.boolean()}); 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 }; /** * Find canonical carrier slugs (beta) * * GET /carriers */ export const getApiCarriers = async (args: GetApiCarriersArgs, options: GetApiCarriersOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (args.transport_mode != null) query.append("transport_mode", String(args.transport_mode)) if (args.limit != null) query.append("limit", String(args.limit)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/carriers${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(deliveryEstimateCarrierSearchResponse, await res.json()) };