Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

51.2 KB
Raw Blame
import type {
  ListParams,
  ListResponse,
  PaginatedResponse,
  RequestFn,
  RequestOptions,
} from '@spree/sdk-core'
import { getParams, transformListParams } from '@spree/sdk-core'
import type {
  AcceptCompanyInvitationParams,
  AddCompanyMemberParams,
  AddLineItemParams,
  Address,
  AddressCreateParams,
  AddressUpdateParams,
  AuthTokens,
  Cart,
  Category,
  CategoryListParams,
  Channel,
  Claim,
  ClaimFilters,
  ClaimSort,
  Collection,
  CollectionListParams,
  Company,
  CompanyAddressCreateParams,
  CompanyAddressUpdateParams,
  CompanyInvitation,
  CompanyInvitationFilters,
  CompanyInvitationSort,
  CompanyMembership,
  CompletePaymentSessionParams,
  CompletePaymentSetupSessionParams,
  Country,
  CreateCartParams,
  CreateClaimParams,
  CreateDataRequestParams,
  CreateNewsletterSubscriberParams,
  CreatePaymentParams,
  CreatePaymentSessionParams,
  CreatePaymentSetupSessionParams,
  CreateReturnParams,
  CreateWishlistItemParams,
  CreateWishlistParams,
  CreditCard,
  Currency,
  Customer,
  DataRequest,
  DeliveryMethod,
  DigitalLink,
  DigitalLinkFilters,
  DigitalLinkSort,
  GiftCard,
  Locale,
  LoginCredentials,
  LogoutParams,
  Market,
  NewsletterSubscriber,
  Order,
  OrderGroup,
  OrderListParams,
  Payment,
  PaymentSession,
  PaymentSetupSession,
  Policy,
  Product,
  ProductFiltersParams,
  ProductFiltersResponse,
  ProductListParams,
  RefreshTokenParams,
  RegisterParams,
  RequestNewsletterUnsubscribeParams,
  RequestPasswordResetParams,
  ResetPasswordParams,
  Return,
  ReturnFilters,
  ReturnSort,
  Seller,
  StockLocation,
  Store,
  StoreCredit,
  UpdateCartParams,
  UpdateCompanyParams,
  UpdateCustomerParams,
  UpdateFulfillmentParams,
  UpdateLineItemParams,
  UpdatePaymentSessionParams,
  UpdateWishlistItemParams,
  UpdateWishlistParams,
  VerifyNewsletterSubscriberParams,
  Wishlist,
  WishlistItem,
} from './types'
import type {
  AddressFilters,
  AddressSort,
  CompanyMembershipFilters,
  CompanyMembershipSort,
  CreditCardFilters,
  CreditCardSort,
  GiftCardFilters,
  GiftCardSort,
  OrderFilters,
  OrderSort,
  SellerFilters,
  SellerSort,
  StoreCreditFilters,
  StoreCreditSort,
  WishlistFilters,
  WishlistSort,
} from './types/filters.generated'

// The category and collection go at the top level; only the filters are Ransack params.
function getFiltersParams(params: ProductFiltersParams = {}) {
  const { q, ...scope } = params
  return { ...scope, ...transformListParams({ q }) }
}

interface ApplyStoreCredit {
  /**
   * Apply store credit to the cart
   * @param cartId - Cart prefixed ID
   * @param amount - How much to apply, as a decimal string (`'10.00'`). Omit it to apply as much
   *   as the cart can use.
   */
  (cartId: string, amount?: string, options?: RequestOptions): Promise<Cart>
  /** @deprecated Pass the amount as a decimal string (`'25.00'`). A number is refused from 6.1. */
  (cartId: string, amount: number, options?: RequestOptions): Promise<Cart>
}

export class StoreClient {
  /**
   * Low-level request function for calling custom API endpoints.
   *
   * Uses the same auth headers, retry logic, and base URL as all built-in resources.
   * Paths are relative to `/api/v3/store`.
   *
   * @example
   * ```ts
   * const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
   * ```
   */
  readonly request: RequestFn

  constructor(request: RequestFn) {
    this.request = request
  }

  // ============================================
  // Authentication
  // ============================================

  readonly auth = {
    /**
     * Login with email and password
     */
    login: (credentials: LoginCredentials): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', '/auth/login', { body: credentials }),

    /**
     * Refresh access token using a refresh token.
     * Returns new access JWT + rotated refresh token.
     * No Authorization header needed — uses refresh_token in body.
     */
    refresh: (params: RefreshTokenParams, options?: RequestOptions): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', '/auth/refresh', { ...options, body: params }),

    /**
     * Logout — revokes the refresh token.
     */
    logout: (params: LogoutParams, options?: RequestOptions): Promise<void> =>
      this.request<void>('POST', '/auth/logout', { ...options, body: params }),
  }

  // ============================================
  // Products
  // ============================================

  readonly products = {
    /**
     * List products
     */
    list: (
      params?: ProductListParams,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Product>> =>
      this.request<PaginatedResponse<Product>>('GET', '/products', {
        ...options,
        params: transformListParams({ ...params }),
      }),

    /**
     * Get a product by ID or slug
     */
    get: (
      idOrSlug: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Product> =>
      this.request<Product>('GET', `/products/${idOrSlug}`, {
        ...options,
        params: getParams(params),
      }),

    /**
     * Get available filters for products
     * Returns filter options (price range, availability, option types, categories) with counts
     */
    filters: (
      params?: ProductFiltersParams,
      options?: RequestOptions,
    ): Promise<ProductFiltersResponse> =>
      this.request<ProductFiltersResponse>('GET', '/products/filters', {
        ...options,
        params: getFiltersParams(params),
      }),
  }

  // ============================================
  // Categories
  // ============================================

  readonly categories = {
    /**
     * List categories
     */
    list: (
      params?: CategoryListParams,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Category>> =>
      this.request<PaginatedResponse<Category>>('GET', '/categories', {
        ...options,
        params: transformListParams({ ...params }),
      }),

    /**
     * Get a category by ID or permalink
     */
    get: (
      idOrPermalink: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Category> =>
      this.request<Category>('GET', `/categories/${idOrPermalink}`, {
        ...options,
        params: getParams(params),
      }),
  }

  /**
   * Collections — flat, merchandising-driven product groupings ("Summer Sale",
   * "New Arrivals"). Membership may be curated by the merchant or maintained
   * automatically from rules; either way it reads the same from the storefront.
   */
  /**
   * Public seller profiles on a marketplace. Only sellers a shopper can
   * currently buy from are listed — see the Store Sellers endpoint.
   */
  readonly sellers = {
    /**
     * List sellers. Paginated like every other collection (`page`, `limit`),
     * and filterable through Ransack — `q[name_cont]` for a name search,
     * `sort` for ordering.
     *
     * Only sellers a shopper can currently buy from are returned; one still
     * onboarding, suspended, or away on holiday is omitted.
     */
    list: (
      params?: ListParams<SellerFilters, SellerSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Seller>> =>
      this.request<PaginatedResponse<Seller>>('GET', '/sellers', {
        ...options,
        params: transformListParams({ ...params }),
      }),

    /** By slug or prefixed ID, so a storefront can route `/sellers/sparks-audio`. */
    get: (
      idOrSlug: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Seller> =>
      this.request<Seller>('GET', `/sellers/${idOrSlug}`, {
        ...options,
        params: getParams(params),
      }),
  }

  readonly collections = {
    /**
     * List collections
     */
    list: (
      params?: CollectionListParams,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Collection>> =>
      this.request<PaginatedResponse<Collection>>('GET', '/collections', {
        ...options,
        params: transformListParams({ ...params }),
      }),

    /**
     * Get a collection by ID or permalink
     */
    get: (
      idOrPermalink: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Collection> =>
      this.request<Collection>('GET', `/collections/${idOrPermalink}`, {
        ...options,
        params: getParams(params),
      }),

    products: {
      /**
       * List the products in a collection — the collection's product listing
       * page. Accepts the same filters and sorts as `products.list`; when
       * `sort` is omitted the collection's own `sort_order` applies, so a
       * merchant's chosen ordering (including their manual arrangement) is
       * what a shopper sees by default.
       */
      list: (
        idOrPermalink: string,
        params?: ProductListParams,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Product>> =>
        this.request<PaginatedResponse<Product>>('GET', `/collections/${idOrPermalink}/products`, {
          ...options,
          params: transformListParams({ ...params }),
        }),
    },
  }

  // ============================================
  // Countries, Currencies & Locales
  // ============================================

  readonly countries = {
    /**
     * List countries available in the store
     * Each country includes currency and default_locale derived from its market
     */
    list: (options?: RequestOptions): Promise<ListResponse<Country>> =>
      this.request<ListResponse<Country>>('GET', '/countries', options),

    /**
     * Get a country by ISO code
     * Use `?expand=states` to expand states for address forms
     * @param iso - ISO 3166-1 alpha-2 code (e.g., "US", "DE")
     */
    get: (
      iso: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Country> =>
      this.request<Country>('GET', `/countries/${iso}`, {
        ...options,
        params: getParams(params),
      }),
  }

  readonly currencies = {
    /**
     * List currencies supported by the store (derived from markets)
     */
    list: (options?: RequestOptions): Promise<ListResponse<Currency>> =>
      this.request<ListResponse<Currency>>('GET', '/currencies', options),
  }

  readonly locales = {
    /**
     * List locales supported by the store (derived from markets)
     */
    list: (options?: RequestOptions): Promise<ListResponse<Locale>> =>
      this.request<ListResponse<Locale>>('GET', '/locales', options),
  }

  readonly channel = {
    /**
     * Get the channel this client's requests resolve to (API-key binding →
     * `channel` client option → store default), including the resolved
     * `storefront_access` posture (`public` | `prices_hidden` |
     * `login_required`) and whether guest checkout is allowed. Reachable
     * before authentication so gated storefronts can render a sign-in wall.
     */
    get: (options?: RequestOptions): Promise<Channel> =>
      this.request<Channel>('GET', '/channel', options),
  }

  readonly store = {
    /**
     * Get the current store's name and default SEO metadata (`seo_title`,
     * `meta_description`) in the request locale. A field without a
     * translation falls back to the store's default locale.
     */
    get: (options?: RequestOptions): Promise<Store> =>
      this.request<Store>('GET', '/store', options),
  }

  // ============================================
  // Policies
  // ============================================

  readonly deliveryMethods = {
    /**
     * List storefront-visible delivery methods.
     * Filter by fulfillment_type to discover pickup options.
     */
    list: (
      params?: { fulfillment_type?: 'shipping' | 'digital' | 'pickup' | 'pickup_point' },
      options?: RequestOptions,
    ): Promise<ListResponse<DeliveryMethod>> =>
      this.request<ListResponse<DeliveryMethod>>('GET', '/delivery_methods', {
        ...options,
        params: params,
      }),

    get: (id: string, options?: RequestOptions): Promise<DeliveryMethod> =>
      this.request<DeliveryMethod>('GET', `/delivery_methods/${id}`, options),

    /**
     * Pickup-enabled stock locations for a pickup delivery method.
     * Pass cart_id to keep only locations able to fulfill the whole cart
     * from local stock.
     */
    pickupLocations: (
      id: string,
      params?: { cart_id?: string },
      options?: RequestOptions,
    ): Promise<{ data: StockLocation[] }> =>
      this.request<{ data: StockLocation[] }>('GET', `/delivery_methods/${id}/pickup_locations`, {
        ...options,
        params: params,
      }),

    /** Third-party pickup points near the customer (pickup_point methods). */
    pickupPoints: (
      id: string,
      params: { latitude: number; longitude: number },
      options?: RequestOptions,
    ): Promise<{ data: Array<Record<string, unknown>> }> =>
      this.request<{ data: Array<Record<string, unknown>> }>(
        'GET',
        `/delivery_methods/${id}/pickup_points`,
        {
          ...options,
          params: params,
        },
      ),
  }

  readonly policies = {
    /**
     * List store policies (return policy, privacy policy, terms of service, etc.)
     */
    list: (options?: RequestOptions): Promise<ListResponse<Policy>> =>
      this.request<ListResponse<Policy>>('GET', '/policies', options),

    /**
     * Get a policy by slug or prefixed ID
     * @param id - Policy slug (e.g., 'return-policy') or prefixed ID (e.g., 'pol_abc123')
     */
    get: (id: string, options?: RequestOptions): Promise<Policy> =>
      this.request<Policy>('GET', `/policies/${id}`, options),
  }

  // ============================================
  // Markets
  // ============================================

  readonly markets = {
    /**
     * List all markets for the current store
     */
    list: (options?: RequestOptions): Promise<ListResponse<Market>> =>
      this.request<ListResponse<Market>>('GET', '/markets', options),

    /**
     * Get a market by prefixed ID
     * @param id - Market prefixed ID (e.g., "mkt_k5nR8xLq")
     */
    get: (id: string, options?: RequestOptions): Promise<Market> =>
      this.request<Market>('GET', `/markets/${id}`, options),

    /**
     * Resolve which market applies for a given country
     * @param country - ISO 3166-1 alpha-2 code (e.g., "DE", "US")
     */
    resolve: (country: string, options?: RequestOptions): Promise<Market> =>
      this.request<Market>('GET', '/markets/resolve', {
        ...options,
        params: { country },
      }),

    /**
     * Nested resource: Countries in a market
     */
    countries: {
      /**
       * List countries belonging to a market
       * @param marketId - Market prefixed ID
       */
      list: (marketId: string, options?: RequestOptions): Promise<ListResponse<Country>> =>
        this.request<ListResponse<Country>>('GET', `/markets/${marketId}/countries`, options),

      /**
       * Get a country by ISO code within a market
       * @param marketId - Market prefixed ID
       * @param iso - Country ISO code (e.g., "DE")
       */
      get: (
        marketId: string,
        iso: string,
        params?: { expand?: string[]; fields?: string[] },
        options?: RequestOptions,
      ): Promise<Country> =>
        this.request<Country>('GET', `/markets/${marketId}/countries/${iso}`, {
          ...options,
          params: getParams(params),
        }),
    },
  }

  // ============================================
  // Carts
  // ============================================

  readonly carts = {
    /**
     * List all active (incomplete) carts for the authenticated user
     */
    list: (options?: RequestOptions): Promise<PaginatedResponse<Cart>> =>
      this.request<PaginatedResponse<Cart>>('GET', '/carts', options),

    /**
     * Get a cart by prefixed ID
     * @param cartId - Cart prefixed ID (e.g., "cart_abc123")
     */
    get: (cartId: string, options?: RequestOptions): Promise<Cart> =>
      this.request<Cart>('GET', `/carts/${cartId}`, options),

    /**
     * Create a new cart
     * @param params - Optional cart parameters (e.g., metadata, items)
     */
    create: (params?: CreateCartParams, options?: RequestOptions): Promise<Cart> =>
      this.request<Cart>('POST', '/carts', {
        ...options,
        body: params,
      }),

    /**
     * Update a cart (email, addresses, special instructions)
     * @param cartId - Cart prefixed ID
     * @param params - Cart update parameters
     */
    update: (cartId: string, params: UpdateCartParams, options?: RequestOptions): Promise<Cart> =>
      this.request<Cart>('PATCH', `/carts/${cartId}`, {
        ...options,
        body: params,
      }),

    /**
     * Delete/abandon a cart
     * @param cartId - Cart prefixed ID
     */
    delete: (cartId: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/carts/${cartId}`, options),

    /**
     * Associate a guest cart with the currently authenticated user
     * @param cartId - Cart prefixed ID
     * @param options - Must include `token` (JWT) for authentication
     */
    associate: (cartId: string, options: RequestOptions): Promise<Cart> =>
      this.request<Cart>('PATCH', `/carts/${cartId}/associate`, options),

    /**
     * Complete the cart and finalize the purchase.
     * Returns an Order (not Cart). In a marketplace, a cart holding several
     * sellers' goods divides into one order per seller, and the group it
     * produced is what comes back — narrow the result with `isOrderGroup`.
     * @param cartId - Cart prefixed ID
     */
    complete: (cartId: string, options?: RequestOptions): Promise<Order | OrderGroup> =>
      this.request<Order | OrderGroup>('POST', `/carts/${cartId}/complete`, options),

    /**
     * Nested resource: the addresses this cart may be shipped or billed to —
     * the buyer's own book, plus the book of the company set as the cart's
     * `company_id` and the sites that company inherits from the ones above
     * it, limited to the countries the cart's market sells to. Every address
     * listed here is accepted as `shipping_address_id` or `billing_address_id`
     * on the cart.
     *
     * Requires a customer JWT (`token`), unlike the rest of the cart calls: it
     * returns the account's address books rather than the cart's own data, so a
     * guest cart token is not accepted. A guest cart has neither book anyway.
     */
    addresses: {
      /**
       * List the addresses this cart may use. Requires a customer JWT.
       * @param cartId - Cart prefixed ID
       */
      list: (
        cartId: string,
        params?: ListParams<AddressFilters, AddressSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Address>> =>
        this.request<PaginatedResponse<Address>>('GET', `/carts/${cartId}/addresses`, {
          ...options,
          params: transformListParams({ ...params }),
        }),
    },

    /**
     * Nested resource: Line items
     */
    items: {
      /**
       * Add an item to the cart.
       * Returns the updated cart with recalculated totals.
       * @param cartId - Cart prefixed ID
       */
      create: (
        cartId: string,
        params: AddLineItemParams,
        options?: RequestOptions,
      ): Promise<Cart> =>
        this.request<Cart>('POST', `/carts/${cartId}/items`, {
          ...options,
          body: params,
        }),

      /**
       * Update a line item quantity.
       * Returns the updated cart with recalculated totals.
       * @param cartId - Cart prefixed ID
       */
      update: (
        cartId: string,
        lineItemId: string,
        params: UpdateLineItemParams,
        options?: RequestOptions,
      ): Promise<Cart> =>
        this.request<Cart>('PATCH', `/carts/${cartId}/items/${lineItemId}`, {
          ...options,
          body: params,
        }),

      /**
       * Remove a line item from the cart.
       * Returns the updated cart with recalculated totals.
       * @param cartId - Cart prefixed ID
       */
      delete: (cartId: string, lineItemId: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('DELETE', `/carts/${cartId}/items/${lineItemId}`, options),
    },

    /**
     * Nested resource: Discount codes
     */
    discountCodes: {
      /**
       * Apply a discount code to the cart
       * @param cartId - Cart prefixed ID
       * @param code - Promotion discount code to apply (e.g., 'SAVE10')
       */
      apply: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('POST', `/carts/${cartId}/discount_codes`, {
          ...options,
          body: { code },
        }),

      /**
       * Remove a discount code from the cart
       * @param cartId - Cart prefixed ID
       * @param code - The discount code string to remove (e.g., 'SAVE10')
       */
      remove: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('DELETE', `/carts/${cartId}/discount_codes/${code}`, options),
    },

    /**
     * Nested resource: Gift cards
     */
    giftCards: {
      /**
       * Apply a gift card to the cart.
       * Gift cards are treated as a payment method — the cart total remains unchanged
       * while `amount_due` is reduced.
       * @param cartId - Cart prefixed ID
       * @param code - Gift card code to apply
       */
      apply: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('POST', `/carts/${cartId}/gift_cards`, {
          ...options,
          body: { code },
        }),

      /**
       * Remove the applied gift card from the cart
       * @param cartId - Cart prefixed ID
       * @param giftCardId - Gift card prefixed ID (e.g., 'gc_abc123')
       */
      remove: (cartId: string, giftCardId: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('DELETE', `/carts/${cartId}/gift_cards/${giftCardId}`, options),
    },

    /**
     * Nested resource: Fulfillments
     */
    fulfillments: {
      /**
       * Select a delivery rate for a specific fulfillment.
       * Returns the updated cart with recalculated totals.
       * @param cartId - Cart prefixed ID
       */
      update: (
        cartId: string,
        fulfillmentId: string,
        params: UpdateFulfillmentParams,
        options?: RequestOptions,
      ): Promise<Cart> =>
        this.request<Cart>('PATCH', `/carts/${cartId}/fulfillments/${fulfillmentId}`, {
          ...options,
          body: params,
        }),
    },

    /**
     * Nested resource: Payments
     */
    payments: {
      /**
       * Create a payment for a non-session payment method (e.g. Check, Cash on Delivery, Bank Transfer).
       * For session-based payment methods (e.g. Stripe, PayPal), use carts.paymentSessions.create() instead.
       * @param cartId - Cart prefixed ID
       */
      create: (
        cartId: string,
        params: CreatePaymentParams,
        options?: RequestOptions,
      ): Promise<Payment> =>
        this.request<Payment>('POST', `/carts/${cartId}/payments`, { ...options, body: params }),
    },

    /**
     * Nested resource: Payment sessions
     */
    paymentSessions: {
      /**
       * Create a payment session for the cart.
       * Delegates to the payment gateway to initialize a provider-specific session.
       * @param cartId - Cart prefixed ID
       */
      create: (
        cartId: string,
        params: CreatePaymentSessionParams,
        options?: RequestOptions,
      ): Promise<PaymentSession> =>
        this.request<PaymentSession>('POST', `/carts/${cartId}/payment_sessions`, {
          ...options,
          body: params,
        }),

      /**
       * Get a payment session by ID
       * @param cartId - Cart prefixed ID
       */
      get: (cartId: string, sessionId: string, options?: RequestOptions): Promise<PaymentSession> =>
        this.request<PaymentSession>(
          'GET',
          `/carts/${cartId}/payment_sessions/${sessionId}`,
          options,
        ),

      /**
       * Update a payment session.
       * Delegates to the payment gateway to sync changes with the provider.
       * @param cartId - Cart prefixed ID
       */
      update: (
        cartId: string,
        sessionId: string,
        params: UpdatePaymentSessionParams,
        options?: RequestOptions,
      ): Promise<PaymentSession> =>
        this.request<PaymentSession>('PATCH', `/carts/${cartId}/payment_sessions/${sessionId}`, {
          ...options,
          body: params,
        }),

      /**
       * Complete a payment session.
       * Confirms the payment with the provider, triggering capture/authorization.
       * @param cartId - Cart prefixed ID
       */
      complete: (
        cartId: string,
        sessionId: string,
        params?: CompletePaymentSessionParams,
        options?: RequestOptions,
      ): Promise<PaymentSession> =>
        this.request<PaymentSession>(
          'PATCH',
          `/carts/${cartId}/payment_sessions/${sessionId}/complete`,
          { ...options, body: params },
        ),
    },

    /**
     * Store credits
     */
    storeCredits: {
      apply: ((cartId: string, amount?: string | number, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('POST', `/carts/${cartId}/store_credits`, {
          ...options,
          body: amount != null && amount !== '' ? { amount } : undefined,
        })) as ApplyStoreCredit,

      /**
       * Remove store credit from the cart
       * @param cartId - Cart prefixed ID
       */
      remove: (cartId: string, options?: RequestOptions): Promise<Cart> =>
        this.request<Cart>('DELETE', `/carts/${cartId}/store_credits`, options),
    },
  }

  // ============================================
  // Orders (post-purchase, read-only)
  // ============================================

  readonly orders = {
    /**
     * Get a completed order by prefixed ID.
     * Accessible via JWT (authenticated users) or spreeToken (guests).
     *
     * Also accepts the id of the cart the checkout was placed from — the
     * handle a storefront still holds on its confirmation page. A checkout
     * that reached several sellers resolves there to the group of orders it
     * produced rather than to any one of them, exactly as `carts.complete`
     * answered it; narrow the result with `isOrderGroup`.
     */
    get: (
      id: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Order | OrderGroup> =>
      this.request<Order | OrderGroup>('GET', `/orders/${id}`, {
        ...options,
        params: getParams(params),
      }),

    /**
     * Returns the customer opened on this order.
     *
     * Opening one is all a customer can do — approving, receiving and
     * refunding are the merchant's, through the Admin API. Whether they may
     * open one at all is store policy, enforced by a `returns.create.validate`
     * handler on the server; a rejected request comes back as a 422.
     */
    returns: {
      list: (
        orderId: string,
        params?: ListParams<ReturnFilters, ReturnSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Return>> =>
        this.request<PaginatedResponse<Return>>('GET', `/orders/${orderId}/returns`, {
          ...options,
          params: params ? transformListParams({ ...params }) : undefined,
        }),

      get: (
        orderId: string,
        id: string,
        params?: { expand?: string[] },
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('GET', `/orders/${orderId}/returns/${id}`, {
          ...options,
          params: getParams(params),
        }),

      /**
       * @param params.items the fulfilled units coming back. `fulfillment_item_id`
       *   rather than a line item id, because a return is against a shipped unit.
       */
      create: (
        orderId: string,
        params: CreateReturnParams,
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('POST', `/orders/${orderId}/returns`, {
          ...options,
          body: params,
        }),

      /**
       * The prepaid return label the merchant bought, if there is one — the
       * path to fetch it from. The bytes are streamed through the API rather
       * than served from storage, so fetch this with the customer's
       * credentials and drive the browser download from a Blob; a 404 means no
       * label was bought.
       */
      labelPath: (orderId: string, id: string): string =>
        `/api/v3/store/orders/${orderId}/returns/${id}/label`,
    },

    /**
     * Claims the customer filed on this order — a damaged, missing or wrong
     * item. Nothing has to come back, so unlike a return this works whether or
     * not the order shipped. Approving, denying and resolving are the
     * merchant's.
     */
    claims: {
      list: (
        orderId: string,
        params?: ListParams<ClaimFilters, ClaimSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Claim>> =>
        this.request<PaginatedResponse<Claim>>('GET', `/orders/${orderId}/claims`, {
          ...options,
          params: params ? transformListParams({ ...params }) : undefined,
        }),

      get: (
        orderId: string,
        id: string,
        params?: { expand?: string[] },
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('GET', `/orders/${orderId}/claims/${id}`, {
          ...options,
          params: getParams(params),
        }),

      /**
       * @param params.reason_id one of the store's claim reasons
       */
      create: (
        orderId: string,
        params: CreateClaimParams,
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('POST', `/orders/${orderId}/claims`, {
          ...options,
          body: params,
        }),
    },
  }

  // ============================================
  // Customer
  // ============================================

  readonly customers = {
    /**
     * Register a new customer account
     */
    create: (params: RegisterParams): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', '/customers', { body: params }),
  }

  // ============================================
  // Newsletter Subscribers
  // ============================================

  readonly newsletterSubscribers = {
    /**
     * Subscribe an email address to the newsletter for the current store.
     * Guests get an unverified record; pass a JWT via `options.token` to link
     * to a customer (auto-verifies when the JWT email matches `params.email`).
     * `redirect_url` is dropped from the webhook payload when it's not in the
     * store's allowed origins.
     */
    create: (
      params: CreateNewsletterSubscriberParams,
      options?: RequestOptions,
    ): Promise<NewsletterSubscriber> =>
      this.request<NewsletterSubscriber>('POST', '/newsletter_subscribers', {
        ...options,
        body: params,
      }),

    /**
     * Confirm a pending subscription using the token from the confirmation email.
     */
    verify: (
      params: VerifyNewsletterSubscriberParams,
      options?: RequestOptions,
    ): Promise<NewsletterSubscriber> =>
      this.request<NewsletterSubscriber>('POST', '/newsletter_subscribers/verify', {
        ...options,
        body: params,
      }),

    /**
     * Request an unsubscribe link for an email address. When a subscriber
     * exists, a `newsletter_subscriber.unsubscribe_requested` webhook event
     * fires carrying the unsubscribe token; the response is always 202 to
     * prevent email enumeration. `redirect_url` is dropped from the webhook
     * payload when it's not in the store's allowed origins.
     */
    requestUnsubscribe: (
      params: RequestNewsletterUnsubscribeParams,
      options?: RequestOptions,
    ): Promise<void> =>
      this.request<void>('POST', '/newsletter_subscribers/request_unsubscribe', {
        ...options,
        body: params,
      }),

    /**
     * Unsubscribe from the newsletter. Pass a JWT via `options.token` for a
     * signed-in customer removing their own subscription (its id comes from
     * `customer.newsletter_subscriber` on GET /customers/me), or
     * `params.token` with the unsubscribe token from an email link.
     */
    delete: (id: string, params?: { token?: string }, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/newsletter_subscribers/${id}`, {
        ...options,
        params: params?.token ? { token: params.token } : undefined,
      }),
  }

  readonly customer = {
    /**
     * Get current customer profile
     */
    get: (options?: RequestOptions): Promise<Customer> =>
      this.request<Customer>('GET', '/customers/me', options),

    /**
     * Update current customer profile
     */
    update: (params: UpdateCustomerParams, options?: RequestOptions): Promise<Customer> =>
      this.request<Customer>('PATCH', '/customers/me', {
        ...options,
        body: params,
      }),

    /**
     * Nested resource: Addresses
     */
    addresses: {
      /**
       * List customer addresses
       */
      list: (
        params?: ListParams<AddressFilters, AddressSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Address>> =>
        this.request<PaginatedResponse<Address>>('GET', '/customers/me/addresses', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get an address by ID
       */
      get: (id: string, options?: RequestOptions): Promise<Address> =>
        this.request<Address>('GET', `/customers/me/addresses/${id}`, options),

      /**
       * Create an address
       */
      create: (params: AddressCreateParams, options?: RequestOptions): Promise<Address> =>
        this.request<Address>('POST', '/customers/me/addresses', {
          ...options,
          body: params,
        }),

      /**
       * Update an address
       */
      update: (
        id: string,
        params: AddressUpdateParams,
        options?: RequestOptions,
      ): Promise<Address> =>
        this.request<Address>('PATCH', `/customers/me/addresses/${id}`, {
          ...options,
          body: params,
        }),

      /**
       * Delete an address
       */
      delete: (id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/customers/me/addresses/${id}`, options),
    },

    /**
     * Nested resource: GDPR data requests (a copy of the customer's data, or its erasure)
     */
    dataRequests: {
      /**
       * List the customer's data requests, most recent first
       */
      list: (
        params?: ListParams,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<DataRequest>> =>
        this.request<PaginatedResponse<DataRequest>>('GET', '/customers/me/data_requests', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get one of the customer's data requests. Never carries the download
       * link: that goes only to the holder of the emailed confirmation token.
       */
      get: (id: string, options?: RequestOptions): Promise<DataRequest> =>
        this.request<DataRequest>('GET', `/customers/me/data_requests/${id}`, options),

      /**
       * Open a data request. Nothing happens until it is confirmed from the
       * link emailed to the customer's address, which opens `redirect_url`
       * with the token appended (see `client.dataRequests.confirm`). Erasure
       * needs `current_password`.
       */
      create: (params?: CreateDataRequestParams, options?: RequestOptions): Promise<DataRequest> =>
        this.request<DataRequest>('POST', '/customers/me/data_requests', {
          ...options,
          body: params,
        }),
    },

    /**
     * Nested resource: Credit Cards
     */
    creditCards: {
      /**
       * List customer credit cards
       */
      list: (
        params?: ListParams<CreditCardFilters, CreditCardSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<CreditCard>> =>
        this.request<PaginatedResponse<CreditCard>>('GET', '/customers/me/credit_cards', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get a credit card by ID
       */
      get: (id: string, options?: RequestOptions): Promise<CreditCard> =>
        this.request<CreditCard>('GET', `/customers/me/credit_cards/${id}`, options),

      /**
       * Delete a credit card
       */
      delete: (id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/customers/me/credit_cards/${id}`, options),
    },

    /**
     * Nested resource: Gift Cards
     */
    giftCards: {
      /**
       * List customer gift cards
       * Returns gift cards associated with the current user, ordered by newest first
       */
      list: (
        params?: ListParams<GiftCardFilters, GiftCardSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<GiftCard>> =>
        this.request<PaginatedResponse<GiftCard>>('GET', '/customers/me/gift_cards', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get a gift card by ID
       */
      get: (id: string, options?: RequestOptions): Promise<GiftCard> =>
        this.request<GiftCard>('GET', `/customers/me/gift_cards/${id}`, options),
    },

    /**
     * Nested resource: Store Credits
     */
    storeCredits: {
      /**
       * List store credits for the authenticated customer.
       * Filtered by current store and currency.
       * Supports Ransack filtering (e.g. `q[amount_remaining_gt]: 0`).
       */
      list: (
        params?: ListParams<StoreCreditFilters, StoreCreditSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<StoreCredit>> =>
        this.request<PaginatedResponse<StoreCredit>>('GET', '/customers/me/store_credits', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get a store credit by ID
       */
      get: (id: string, options?: RequestOptions): Promise<StoreCredit> =>
        this.request<StoreCredit>('GET', `/customers/me/store_credits/${id}`, options),
    },

    /**
     * Nested resource: Digital Links
     *
     * Everything the signed-in customer can download, across all their
     * completed orders — the data behind a "my downloads" page.
     */
    digitalLinks: {
      /**
       * List the customer's downloads, newest first.
       */
      list: (
        params?: ListParams<DigitalLinkFilters, DigitalLinkSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<DigitalLink>> =>
        this.request<PaginatedResponse<DigitalLink>>('GET', '/customers/me/digital_links', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get one download by ID. Each record carries a `download_url` — point the
       * browser at it; the response redirects to short-lived storage, so follow
       * redirects rather than reading the body.
       */
      get: (id: string, options?: RequestOptions): Promise<DigitalLink> =>
        this.request<DigitalLink>('GET', `/customers/me/digital_links/${id}`, options),
    },

    /**
     * Nested resource: Orders (customer order history)
     */
    orders: {
      /**
       * List completed orders for the authenticated customer
       */
      list: (
        params?: OrderListParams,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Order>> =>
        this.request<PaginatedResponse<Order>>('GET', '/customers/me/orders', {
          ...options,
          params: transformListParams({ ...params }),
        }),

      /**
       * Get a completed order by prefixed ID
       */
      get: (
        id: string,
        params?: { expand?: string[]; fields?: string[] },
        options?: RequestOptions,
      ): Promise<Order> =>
        this.request<Order>('GET', `/customers/me/orders/${id}`, {
          ...options,
          params: getParams(params),
        }),
    },

    /**
     * Nested resource: Payment Setup Sessions (save payment methods for future use)
     */
    paymentSetupSessions: {
      /**
       * Create a payment setup session
       * Delegates to the payment gateway to initialize a setup flow for saving a payment method
       */
      create: (
        params: CreatePaymentSetupSessionParams,
        options?: RequestOptions,
      ): Promise<PaymentSetupSession> =>
        this.request<PaymentSetupSession>('POST', '/customers/me/payment_setup_sessions', {
          ...options,
          body: params,
        }),

      /**
       * Get a payment setup session by ID
       */
      get: (id: string, options?: RequestOptions): Promise<PaymentSetupSession> =>
        this.request<PaymentSetupSession>(
          'GET',
          `/customers/me/payment_setup_sessions/${id}`,
          options,
        ),

      /**
       * Complete a payment setup session
       * Confirms the setup with the provider, resulting in a saved payment method
       */
      complete: (
        id: string,
        params?: CompletePaymentSetupSessionParams,
        options?: RequestOptions,
      ): Promise<PaymentSetupSession> =>
        this.request<PaymentSetupSession>(
          'PATCH',
          `/customers/me/payment_setup_sessions/${id}/complete`,
          { ...options, body: params },
        ),
    },
  }

  // ============================================
  // Data Requests (by confirmation token)
  // ============================================

  readonly dataRequests = {
    /**
     * Get the data request a confirmation token belongs to, with the download
     * link once the export is ready. Needs no signed-in customer.
     */
    get: (token: string, options?: RequestOptions): Promise<DataRequest> =>
      this.request<DataRequest>('GET', `/data_requests/${encodeURIComponent(token)}`, options),

    /**
     * Confirm a data request with the token from the confirmation email, and
     * start the work. Call it when the person presses a button, never on page
     * load: some mail scanners open links and run the page's scripts.
     */
    confirm: (token: string, options?: RequestOptions): Promise<DataRequest> =>
      this.request<DataRequest>(
        'POST',
        `/data_requests/${encodeURIComponent(token)}/confirmation`,
        options,
      ),
  }

  // ============================================
  // Password Resets
  // ============================================

  readonly passwordResets = {
    /**
     * Request a password reset email.
     * Always succeeds (202) to prevent email enumeration.
     */
    create: (params: RequestPasswordResetParams): Promise<{ message: string }> =>
      this.request<{ message: string }>('POST', '/password_resets', {
        body: params,
      }),

    /**
     * Reset password using the token from the email.
     * Returns a JWT token on success (auto-login).
     * @param token - Password reset token from the email
     */
    update: (token: string, params: ResetPasswordParams): Promise<AuthTokens> =>
      this.request<AuthTokens>('PATCH', `/password_resets/${token}`, { body: params }),
  }

  // ============================================
  // Companies (B2B self-service)
  // ============================================

  /**
   * The signed-in buyer's company directory. Every endpoint requires a
   * customer JWT and standing over the node — a membership on it or an
   * ancestor; within a company, any member may read and manage the directory
   * (roles and approvals are an Enterprise layer).
   */
  readonly account = {
    /** The buyer's memberships, each with its node and ancestor path. */
    companies: (
      options?: RequestOptions,
    ): Promise<{ data: Array<CompanyMembership & { company: Company }> }> =>
      this.request<{ data: Array<CompanyMembership & { company: Company }> }>(
        'GET',
        '/account/companies',
        options,
      ),
  }

  readonly companies = {
    get: (id: string, options?: RequestOptions): Promise<Company> =>
      this.request<Company>('GET', `/companies/${id}`, options),

    update: (id: string, params: UpdateCompanyParams, options?: RequestOptions): Promise<Company> =>
      this.request<Company>('PATCH', `/companies/${id}`, { ...options, body: params }),

    addresses: {
      list: (
        companyId: string,
        params?: ListParams<AddressFilters, AddressSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Address>> =>
        this.request<PaginatedResponse<Address>>('GET', `/companies/${companyId}/addresses`, {
          ...options,
          params: transformListParams({ ...params }),
        }),

      create: (
        companyId: string,
        params: CompanyAddressCreateParams,
        options?: RequestOptions,
      ): Promise<Address> =>
        this.request<Address>('POST', `/companies/${companyId}/addresses`, {
          ...options,
          body: params,
        }),

      update: (
        companyId: string,
        id: string,
        params: CompanyAddressUpdateParams,
        options?: RequestOptions,
      ): Promise<Address> =>
        this.request<Address>('PATCH', `/companies/${companyId}/addresses/${id}`, {
          ...options,
          body: params,
        }),

      delete: (companyId: string, id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/companies/${companyId}/addresses/${id}`, options),
    },

    members: {
      list: (
        companyId: string,
        params?: ListParams<CompanyMembershipFilters, CompanyMembershipSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<CompanyMembership>> =>
        this.request<PaginatedResponse<CompanyMembership>>(
          'GET',
          `/companies/${companyId}/members`,
          {
            ...options,
            params: transformListParams({ ...params }),
          },
        ),

      /**
       * Invites a person by email. Even an existing customer joins only by
       * accepting the emailed invitation, so this always returns the
       * invitation.
       */
      create: (
        companyId: string,
        params: AddCompanyMemberParams,
        options?: RequestOptions,
      ): Promise<CompanyInvitation> =>
        this.request<CompanyInvitation>('POST', `/companies/${companyId}/members`, {
          ...options,
          body: params,
        }),

      /** Withdraws the member's standing. The customer account is untouched. */
      delete: (companyId: string, id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/companies/${companyId}/members/${id}`, options),
    },

    invitations: {
      list: (
        companyId: string,
        params?: ListParams<CompanyInvitationFilters, CompanyInvitationSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<CompanyInvitation>> =>
        this.request<PaginatedResponse<CompanyInvitation>>(
          'GET',
          `/companies/${companyId}/invitations`,
          { ...options, params: transformListParams({ ...params }) },
        ),

      /** Revokes a pending invitation; its token then stops resolving. */
      delete: (companyId: string, id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/companies/${companyId}/invitations/${id}`, options),
    },

    /** Completed purchases across the node's subtree. */
    orders: {
      list: (
        companyId: string,
        params?: ListParams<OrderFilters, OrderSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<Order>> =>
        this.request<PaginatedResponse<Order>>('GET', `/companies/${companyId}/orders`, {
          ...options,
          params: transformListParams({ ...params }),
        }),
    },
  }

  /**
   * Invitations: members revoke by prefixed id; invitees look up and accept
   * by the plaintext token from the invite email (no authentication needed —
   * the token is the credential, and acceptance may register the account).
   */
  readonly companyInvitations = {
    lookup: (
      token: string,
      options?: RequestOptions,
    ): Promise<CompanyInvitation & { company_name: string; store_name: string }> =>
      this.request<CompanyInvitation & { company_name: string; store_name: string }>(
        'GET',
        `/company_invitations/${token}`,
        options,
      ),

    /**
     * Accepts by token: pass a registration payload for a new account (it is
     * created with the invited email), or call authenticated to bind the
     * invitation to the signed-in customer. Returns the created membership.
     */
    accept: (
      token: string,
      params?: AcceptCompanyInvitationParams,
      options?: RequestOptions,
    ): Promise<CompanyMembership> =>
      this.request<CompanyMembership>('POST', `/company_invitations/${token}/accept`, {
        ...options,
        body: params ?? {},
      }),

    /** Revokes a pending invitation (member-authenticated, by prefixed id). */
    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/company_invitations/${id}`, options),
  }

  // ============================================
  // Wishlists
  // ============================================

  readonly wishlists = {
    /**
     * List wishlists
     */
    list: (
      params?: ListParams<WishlistFilters, WishlistSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Wishlist>> =>
      this.request<PaginatedResponse<Wishlist>>('GET', '/wishlists', {
        ...options,
        params: transformListParams({ ...params }),
      }),

    /**
     * Get a wishlist by ID
     */
    get: (
      id: string,
      params?: { expand?: string[]; fields?: string[] },
      options?: RequestOptions,
    ): Promise<Wishlist> =>
      this.request<Wishlist>('GET', `/wishlists/${id}`, {
        ...options,
        params: getParams(params),
      }),

    /**
     * Create a wishlist
     */
    create: (params: CreateWishlistParams, options?: RequestOptions): Promise<Wishlist> =>
      this.request<Wishlist>('POST', '/wishlists', {
        ...options,
        body: params,
      }),

    /**
     * Update a wishlist
     */
    update: (
      id: string,
      params: UpdateWishlistParams,
      options?: RequestOptions,
    ): Promise<Wishlist> =>
      this.request<Wishlist>('PATCH', `/wishlists/${id}`, {
        ...options,
        body: params,
      }),

    /**
     * Delete a wishlist
     */
    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/wishlists/${id}`, options),

    /**
     * Nested resource: Wishlist items
     */
    items: {
      /**
       * Add an item to a wishlist
       */
      create: (
        wishlistId: string,
        params: CreateWishlistItemParams,
        options?: RequestOptions,
      ): Promise<WishlistItem> =>
        this.request<WishlistItem>('POST', `/wishlists/${wishlistId}/items`, {
          ...options,
          body: params,
        }),

      /**
       * Update a wishlist item
       */
      update: (
        wishlistId: string,
        itemId: string,
        params: UpdateWishlistItemParams,
        options?: RequestOptions,
      ): Promise<WishlistItem> =>
        this.request<WishlistItem>('PATCH', `/wishlists/${wishlistId}/items/${itemId}`, {
          ...options,
          body: params,
        }),

      /**
       * Remove an item from a wishlist
       */
      delete: (wishlistId: string, itemId: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/wishlists/${wishlistId}/items/${itemId}`, options),
    },
  }
}