import {z} from 'zod' export type CheckoutRatesShipFrom = {address_type?: string | undefined, address_line1?: string | undefined, address_line2?: string | undefined, address_line3?: string | undefined, city_locality?: string | undefined, state_province?: string | undefined, postal_code: string, country_code: string}; export type CheckoutRatesShipTo = {address_type?: string | undefined, address_line1?: string | undefined, address_line2?: string | undefined, address_line3?: string | undefined, city_locality?: string | undefined, state_province?: string | undefined, postal_code?: string | undefined, country_code?: string | undefined}; export type WeightUnit = 'pound' | 'ounce' | 'gram' | 'kilogram'; export type Weight = {value: number, unit: WeightUnit}; export type DimensionUnit = 'inch' | 'centimeter'; export type Dimensions = {unit: DimensionUnit, length: number, width: number, height: number}; export type CheckoutRatesItem = {name?: string | undefined, quantity?: number | undefined, sku?: string | undefined, price?: number | undefined, weight?: Weight | undefined, dimensions?: Dimensions | undefined}; export type CalculateCheckoutRatesRequestBody = {ship_from?: CheckoutRatesShipFrom | undefined, ship_to: CheckoutRatesShipTo, items: Array, currency?: string | undefined}; export type CreateApiV2CheckoutRatesConfigIdQuotesArgs = {body: CalculateCheckoutRatesRequestBody}; export type CreateApiV2CheckoutRatesConfigIdQuotesOptions = {baseUrl?: string | undefined, apiKeys?: string | undefined, fetch?: typeof fetch | undefined}; export const deliveryPrediction = z.object({delivery_date: z.string().nullable().optional(), confidence_level: z.enum(["high", "low"]).optional()}); export const checkoutRatesRateOption = z.object({quote_id: z.string().optional(), option_id: z.number().int().optional(), option_name: z.string().optional(), type: z.enum(["live_rate", "flat_rate", "free", "local_delivery"]).optional(), carrier_id: z.string().nullable().optional(), service_code: z.string().nullable().optional(), final_amount: z.number().optional(), currency: z.string().optional(), estimated_delivery_days: z.number().int().nullable().optional(), estimated_delivery_date: z.string().nullable().optional(), delivery_prediction: deliveryPrediction.optional()}); export const calculateCheckoutRatesResponseBody = z.object({config_id: z.string().optional(), rates: z.array(checkoutRatesRateOption).optional(), created_at: z.string().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 }; /** * Calculate checkout rates * * POST /v2/checkout_rates/{config_id}/quotes */ export const createApiV2CheckoutRatesConfigIdQuotes = async (args: CreateApiV2CheckoutRatesConfigIdQuotesArgs, options?: CreateApiV2CheckoutRatesConfigIdQuotesOptions) => { const {baseUrl = "https://api.shipstation.com", fetch: fetchFn = fetch, apiKeys} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKeys !== undefined) headers.set("api-key", apiKeys) const url = `${baseUrl.replace(/\/+$/, '')}/v2/checkout_rates/${encodeURIComponent(String(args.config_id))}/quotes${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(calculateCheckoutRatesResponseBody, await res.json()) };