import {z} from 'zod' export type AddressRequest = {address1?: string | undefined, address2?: string | undefined, city?: string | undefined, countryCode?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, phone?: string | undefined, postalCode?: string | undefined, state?: string | undefined}; export type MonetaryAmount = {currency?: ({currencyCode?: string | undefined, defaultFractionDigits?: number | undefined, displayName?: string | undefined, numericCode?: number | undefined, numericCodeAsString?: string | undefined, symbol?: string | undefined}) | undefined, value?: number | undefined}; export type CreateDiscountLineRequest = {amount?: MonetaryAmount | undefined, name?: string | undefined, promoCode?: string | undefined}; export type OrderCreateFulfillmentStatus = 'PENDING' | 'FULFILLED'; export type CreateOrderShipmentRequest = {carrierName: string, service: string, shipDate: string, trackingNumber: string, trackingUrl?: string | undefined}; export type CreateOrderInventoryBehavior = 'DEDUCT' | 'SKIP'; export type OrderCreateLineItemType = 'PHYSICAL_PRODUCT' | 'CUSTOM'; export type CreateLineItemRequest = {lineItemType: OrderCreateLineItemType, nonSaleUnitPrice?: MonetaryAmount | undefined, quantity: number, title?: string | undefined, unitPricePaid: MonetaryAmount, variantId?: string | undefined}; export type TaxInterpretation = 'INCLUSIVE' | 'EXCLUSIVE'; export type CreateShippingLineRequest = {amount: MonetaryAmount, method: string}; export type ShopperFulfillmentNotificationBehavior = 'SEND' | 'SKIP'; export type CreateOrderRequest = {billingAddress?: AddressRequest | undefined, channelName: string, createdOn: string, customerEmail?: string | undefined, discountLines?: Array | undefined, discountTotal?: MonetaryAmount | undefined, externalOrderReference: string, fulfilledOn?: string | undefined, fulfillmentStatus?: OrderCreateFulfillmentStatus | undefined, fulfillments: Array, grandTotal: MonetaryAmount, inventoryBehavior?: CreateOrderInventoryBehavior | undefined, lineItems: Array, priceTaxInterpretation: TaxInterpretation, shippingAddress?: AddressRequest | undefined, shippingLines?: Array | undefined, shippingTotal?: MonetaryAmount | undefined, shopperFulfillmentNotificationBehavior?: ShopperFulfillmentNotificationBehavior | undefined, subtotal?: MonetaryAmount | undefined, taxTotal?: MonetaryAmount | undefined}; export type CreateApi10CommerceOrdersArgs = {'Idempotency-Key': string, Authorization: string, 'User-Agent': string, body: CreateOrderRequest}; export type CreateApi10CommerceOrdersOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const address = z.object({address1: z.string().optional(), address2: z.string().optional(), city: z.string().optional(), countryCode: z.string().optional(), firstName: z.string().optional(), lastName: z.string().optional(), phone: z.string().optional(), postalCode: z.string().optional(), state: z.string().optional()}); export const monetaryAmount = z.object({currency: z.object({currencyCode: z.string().optional(), defaultFractionDigits: z.number().int().optional(), displayName: z.string().optional(), numericCode: z.number().int().optional(), numericCodeAsString: z.string().optional(), symbol: z.string().optional()}).optional(), value: z.number().optional()}); export const discountLine = z.object({amount: monetaryAmount.optional(), description: z.string().optional(), name: z.string().optional(), promoCode: z.string().optional()}); export const formItem = z.object({label: z.string().optional(), value: z.string().optional()}); export const fulfillmentStatus = z.enum(["PENDING", "FULFILLED", "CANCELED"]); export const fulfillment = z.object({carrierName: z.string().optional(), service: z.string().optional(), shipDate: z.string().optional(), trackingNumber: z.string().optional(), trackingUrl: z.string().optional()}); export const orderNote = z.object({content: z.string().optional()}); export const variantOption = z.object({optionName: z.string().optional(), value: z.string().optional()}); export const lineItem = z.object({customizations: z.array(formItem).optional(), height: z.number().optional(), id: z.string().optional(), imageUrl: z.string().optional(), length: z.number().optional(), lineItemType: z.string().optional(), productId: z.string().optional(), productName: z.string().optional(), quantity: z.number().int().optional(), sku: z.string().optional(), unitPricePaid: monetaryAmount.optional(), variantId: z.string().optional(), variantOptions: z.array(variantOption).optional(), weight: z.number().optional(), width: z.number().optional()}); export const paymentState = z.enum(["NOT_CHARGED", "AUTHORIZED", "PAID", "REFUNDED", "PENDING", "FAILED", "REFUND_PENDING", "REFUND_FAILED", "PARTIALLY_PAID"]); export const shippingLine = z.object({amount: monetaryAmount.optional(), method: z.string().optional()}); export const order = z.object({billingAddress: address.optional(), channel: z.string().optional(), channelName: z.string().optional(), createdOn: z.string().optional(), customerEmail: z.string().optional(), customerId: z.string().optional(), discountLines: z.array(discountLine).optional(), discountTotal: monetaryAmount.optional(), externalOrderReference: z.string().optional(), formSubmission: z.array(formItem).optional(), fulfilledOn: z.string().optional(), fulfillmentStatus: fulfillmentStatus.optional(), fulfillments: z.array(fulfillment).optional(), grandTotal: monetaryAmount.optional(), id: z.string().optional(), internalNotes: z.array(orderNote).optional(), lineItems: z.array(lineItem).optional(), modifiedOn: z.string().optional(), orderNumber: z.string().optional(), paymentState: paymentState.optional(), priceTaxInterpretation: z.string().optional(), refundedTotal: monetaryAmount.optional(), shippingAddress: address.optional(), shippingLines: z.array(shippingLine).optional(), shippingOptionName: z.string().optional(), shippingOptionServiceType: z.enum(["FEDEX_GROUND", "FEDEX_GROUND_HOME_DELIVERY", "FEDEX_PRIORITY_OVERNIGHT", "FEDEX_STANDARD_OVERNIGHT", "FEDEX_2_DAY", "FEDEX_2_DAY_AM", "FEDEX_EXPRESS_SAVER", "FEDEX_FIRST_FREIGHT", "FEDEX_FREIGHT_PRIORITY", "FEDEX_FREIGHT_ECONOMY", "FEDEX_FIRST_OVERNIGHT", "FEDEX_SAME_DAY", "FEDEX_SAME_DAY_CITY", "FEDEX_EUROPE_FIRST_INTERNATIONAL_PRIORITY", "FEDEX_INTERNATIONAL_ECONOMY", "FEDEX_INTERNATIONAL_FIRST", "FEDEX_INTERNATIONAL_PRIORITY", "FEDEX_INTERNATIONAL_ECONOMY_FREIGHT", "FEDEX_INTERNATIONAL_PRIORITY_FREIGHT", "UPS_GROUND", "UPS_NEXT_DAY_AIR", "UPS_NEXT_DAY_AIR_SAVER", "UPS_NEXT_DAY_AIR_EARLY_AM", "UPS_TWO_DAY_AIR", "UPS_THREE_DAY_SELECT", "UPS_TWO_DAY_AIR_AM", "USPS_UNKNOWN", "USPS_FIRST_CLASS", "USPS_PRIORITY", "USPS_EXPRESS", "USPS_STANDARD", "USPS_ALL", "USPS_ONLINE", "OTHER"]).optional(), shippingTotal: monetaryAmount.optional(), subtotal: monetaryAmount.optional(), taxTotal: monetaryAmount.optional(), testmode: z.boolean().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 order * * POST /1.0/commerce/orders */ export const createApi10CommerceOrders = async (args: CreateApi10CommerceOrdersArgs, options?: CreateApi10CommerceOrdersOptions) => { const {baseUrl = "https://api.squarespace.com", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args['User-Agent'] != null) headers.set("User-Agent", String(args['User-Agent'])) if (Authorization !== undefined) headers.set('authorization', `Bearer ${Authorization}`) const url = `${baseUrl.replace(/\/+$/, '')}/1.0/commerce/orders${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(order, await res.json()) };