import {z} from 'zod' export type GetApiCartTotalsArgs = {html?: boolean | undefined}; export type GetApiCartTotalsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const totalsResponse = z.object({subtotal: z.string().optional(), subtotal_tax: z.string().optional(), shipping_total: z.string().optional(), shipping_tax: z.string().optional(), shipping_taxes: z.array(z.number()).optional(), discount_total: z.string().optional(), discount_tax: z.string().optional(), cart_contents_total: z.string().optional(), cart_contents_tax: z.string().optional(), cart_contents_taxes: z.array(z.number()).optional(), fee_total: z.string().optional(), fee_tax: z.string().optional(), fee_taxes: z.array(z.number()).optional(), total: z.string().optional(), total_tax: 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 }; /** * Get cart totals * * GET /cart/totals */ export const getApiCartTotals = async (args: GetApiCartTotalsArgs, options?: GetApiCartTotalsOptions) => { const {baseUrl = "https://example-store.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.html != null) query.append("html", String(args.html)) const url = `${baseUrl.replace(/\/+$/, '')}/cart/totals${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(totalsResponse, await res.json()) };