@behio/storefront-sdk 1.18.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,42 +26,94 @@ const storefront = new BehioStorefront({
26
26
  apiKey: 'pk_live_your_key',
27
27
  });
28
28
 
29
- // Fetch products
30
- const { items } = await storefront.catalog.getProducts({ limit: 12 });
31
-
32
- // Add to cart
33
- await storefront.cart.addItem({ productId: items[0].id, quantity: 1 });
34
-
35
- // Checkout
36
- const order = await storefront.checkout.createOrder({
37
- email: 'customer@example.com',
38
- shippingAddress: { firstName: 'Jan', lastName: 'Novak', street: 'Vodickova 12', city: 'Praha', zip: '11000', country: 'CZ' },
29
+ // Fetch products and check the typed result.
30
+ const products = await storefront.catalog.getProducts({limit: 12});
31
+ if (products.error || !products.data.items.length) throw new Error('No products available');
32
+ await storefront.cart.addItem({productId: products.data.items[0].id, quantity: 1});
33
+
34
+ // After the customer enters addresses and selects shipping/payment:
35
+ const previewResult = await storefront.checkout.preview(checkoutInput);
36
+ if (previewResult.error) throw new Error(previewResult.error.message);
37
+ // Render previewResult.data.grandTotal. Wait for the customer to submit.
38
+ const orderResult = await storefront.checkout.createOrder({
39
+ ...checkoutInput,
40
+ previewToken: previewResult.data.previewToken,
39
41
  });
42
+ if (orderResult.error) throw new Error(orderResult.error.message);
43
+ // Redirect to paymentRedirectUrl, or display the receipt for orderResult.data.
44
+
40
45
  ```
41
46
 
47
+ Paid orders may briefly return `contentDeliveryPending: true` while purchased
48
+ files and course access are being assigned. Render this state in the initial
49
+ receipt HTML and refresh the authenticated order detail until it clears. Tell
50
+ the customer that payment was received and that they do not need to place a
51
+ second order. Existing downloads remain usable while other content is pending.
52
+ Behio stores this work with the payment transaction and retries interrupted or
53
+ failed delivery after restart. Repeating delivery preserves access expiry,
54
+ download counters and course progress.
55
+
56
+ ## Product resources and variant pages
57
+
58
+ Render `resolveVariantContent(product, selectedVariant).assetGroups` in the
59
+ initial HTML. A variant with public resources replaces the parent's groups; an
60
+ empty or absent array inherits them. Render every group and respect item order,
61
+ localized titles and sanitized descriptions. Files are normal public links,
62
+ images open at full size, uploaded videos use native controls, and external
63
+ YouTube/Vimeo players load after an explicit click. Preserve Vimeo's unlisted
64
+ privacy hash. These groups never contain purchased download URLs.
65
+
66
+ `requiresShipping` and `isDigital` belong to the selected variant. Use them for
67
+ its delivery information; the cart remains authoritative for the whole order.
68
+ `catalogSiblings` contains separate product pages: render real localized links
69
+ and mark `isCurrent`, preserving the remaining axes in the variant picker.
70
+ Disable values that have no purchasable variant; use `isPurchasable` so zero-stock
71
+ BACKORDER options remain selectable. Clear incompatible axis selections.
72
+
73
+ Product reviews must also be present in the first HTML. Fetch page one on the
74
+ server and pass it as `initialData` to `useProductReviews`; page and limit identify
75
+ the cache entry. Use the selected variant's ID and own rating, render photos and
76
+ merchant replies, and distinguish failures from an empty list. Verified purchase
77
+ requires authenticated order ownership. A helpful vote with `success: false` is
78
+ a duplicate; errors must roll back optimistic counts.
79
+
42
80
  ## React Hooks
43
81
 
82
+ Catalog pricing supports a request-specific `country` alongside `currency` and
83
+ customer authentication. `new BehioStorefront({apiKey, country: 'SK', currency:
84
+ 'EUR'})` resolves country rules on every catalog surface. `setCountry()` changes
85
+ that default; explicit per-call country values win. It does not change the cart:
86
+ use `cart.setDestination()` for that. The Next.js adapter reads `behio_country`
87
+ for the initial server render. Keep authenticated responses private and include
88
+ both currency and country in guest cache keys.
89
+ When initializing a new cart, `cart.setCurrency()` and `cart.setDestination()`
90
+ save its returned session before the next mutation. Templates should initialize
91
+ this context before the first product or bundle is added, including after the
92
+ previous cart expires.
93
+
44
94
  ```tsx
45
- import { BehioProvider, useProducts, useCart, useAddToCart } from '@behio/storefront-sdk/react';
95
+ import { BehioProvider, useProducts, useCart } from '@behio/storefront-sdk/react';
46
96
 
47
97
  function App() {
48
98
  return (
49
- <BehioProvider client={storefront}>
99
+ <BehioProvider apiKey="pk_live_your_key">
50
100
  <ProductList />
51
101
  </BehioProvider>
52
102
  );
53
103
  }
54
104
 
55
105
  function ProductList() {
56
- const { data, isLoading } = useProducts({ limit: 12 });
57
- const addToCart = useAddToCart();
106
+ const { items, isLoading, error } = useProducts({ limit: 12 });
107
+ const { addItem, isAdding } = useCart();
58
108
 
59
109
  if (isLoading) return <div>Loading...</div>;
60
110
 
61
- return data.items.map(p => (
111
+ if (error) return <p role="alert">Products could not be loaded.</p>;
112
+
113
+ return items.map(p => (
62
114
  <div key={p.id}>
63
- <h3>{p.name}, {p.price} {p.currency}</h3>
64
- <button onClick={() => addToCart.mutateAsync({ productId: p.id, quantity: 1 })}>
115
+ <h3>{p.name}, {p.price ? `${p.price.amount} ${p.price.currency}` : "Sign in to view price"}</h3>
116
+ <button disabled={isAdding || !p.isPurchasable} onClick={() => addItem(p.id, 1).catch(() => window.alert("The item could not be added."))}>
65
117
  Add to Cart
66
118
  </button>
67
119
  </div>
@@ -69,6 +121,15 @@ function ProductList() {
69
121
  }
70
122
  ```
71
123
 
124
+ The example above shows browser hook usage. Production templates render the
125
+ initial catalog/cart on the server and hydrate their data. HTTP-only sessions
126
+ stay behind Server Actions or a session-bound API. `useCart()` returns `cart`,
127
+ `isEmpty`, `itemCount` and its mutation methods. Update/removal retain the last
128
+ complete server snapshot while pending and accept the entire successful response,
129
+ even when query fetching is disabled. Failed writes do not roll back newer cache
130
+ values. `isEmpty` includes bundle lines; `itemCount` uses server bundle quantities.
131
+ The provider notifies hooks after restoring browser session storage.
132
+
72
133
  ## What's Included
73
134
 
74
135
  ### SDK Modules
@@ -78,7 +139,7 @@ function ProductList() {
78
139
  | `catalog` | Products, categories, labels, search, filters, bundles, cross-sell, promotions |
79
140
  | `auth` | Register, login, logout, password reset, token refresh |
80
141
  | `cart` | Items, discounts, gift cards, bundles, cart merge |
81
- | `checkout` | Create orders with atomic stock/payment validation |
142
+ | `checkout` | Preview the final total and create orders with a signed price review |
82
143
  | `orders` | List, detail, tracking, cancel |
83
144
  | `customer` | Profile, addresses, password change |
84
145
  | `wishlist` | Add, remove, check |
@@ -94,7 +155,7 @@ function ProductList() {
94
155
 
95
156
  ### React Hooks (30+)
96
157
 
97
- `useProducts` · `useProduct` · `useCategories` · `useCategoryProducts` · `useFeaturedProducts` · `useLabels` · `useProductSearch` · `useFilters` · `useBundles` · `useBundle` · `useCrossSell` · `useProductPromotions` · `useGiftCardBalance` · `useCart` · `useAddToCart` · `useUpdateCartItem` · `useRemoveCartItem` · `useCheckout` · `useOrders` · `useOrder` · `useOrderTracking` · `useCustomerProfile` · `useAddresses` · `useAddressAutocomplete` · `useWishlist` · `useProductReviews` · `useSubmitReview` · `useShopInfo` · `useShopSeo` · `useCartCount` · `useBlogs` · `useBlogPosts` · `useBlogPost` · `useSiteForm` · `useSiteFormSubmit`
158
+ `useProducts` · `useProduct` · `useCategories` · `useFeatured` · `useLabels` · `useSearch` · `useFilters` · `useBundles` · `useBundle` · `useCrossSell` · `useProductPromotions` · `useGiftCardBalance` · `useCart` · `useCheckout` · `useOrders` · `useOrder` · `useCustomer` · `useAddresses` · `useAddressAutocomplete` · `useWishlist` · `useProductReviews` · `useSubmitReview` · `useShopInfo` · `useShopSeo` · `useCartCount` · `useBlogs` · `useBlogPosts` · `useBlogPost` · `useSiteForm` · `useSiteFormSubmit`
98
159
 
99
160
  ### Framework Support
100
161
 
@@ -122,3 +183,132 @@ Full API reference, framework guides, and examples:
122
183
  ## License
123
184
 
124
185
  MIT
186
+
187
+ ## Checkout price review and merchant policies
188
+
189
+ Call `checkout.preview(input)` after the shopper completes delivery and payment choices.
190
+ Render its `grandTotal`, then send its `previewToken` with the final `createOrder` input.
191
+ The token lasts five minutes and is bound to the current cart, prices and choices. A
192
+ changed or expired review returns `be.storefront.checkoutChanged`: refresh the display
193
+ and wait for the shopper to submit again. `useCheckoutPreview` is available for React;
194
+ Server Actions are preferred when storing the guest receipt token in an HttpOnly cookie.
195
+
196
+ `discountTotal` includes loyalty and gift-card deductions. Receipt snapshots add
197
+ `paymentFee`, `roundingAdjustment`, `loyaltyDiscount`, and `giftCardDeducted`; null denotes
198
+ an older order. Never double-subtract a breakdown. Use `cart.checkoutLimits` for min/max
199
+ values in cart currency. Checkout flags, account/password policy, appearance, maintenance,
200
+ SEO and currency display come from the typed shop contract. See the checkout documentation
201
+ for independent legal consents and the exact preview lifecycle.
202
+
203
+
204
+ Physical delivery uses `product.requiresShipping` and `cart.requiresShipping`, independently
205
+ of downloadable bonuses. Online-only orders need a billing address and omit shipping.
206
+ `CourseListItem.isRevoked` and `DigitalDownload.isRevoked` distinguish withdrawn access
207
+ from expiry. Course purchases have independent access periods; retries do not extend
208
+ access, and refunding one purchase preserves another valid purchase.
209
+
210
+ Delivery progress uses `Cart.shippingSubtotal`, after product promotions and before order coupons/loyalty/gift cards. `shippingPromotionApplied` marks an active free-delivery promotion. Method thresholds already include the shop-wide threshold converted into the requested currency. Online carts (`requiresShipping: false`) have no delivery progress.
211
+
212
+ Guest course purchases are linked to an account only after its email address is
213
+ verified, even when email verification is optional for registration. Purchases
214
+ made while authenticated belong to that account. A different checkout receipt
215
+ email cannot claim another account’s courses. Unverified accounts cannot extend
216
+ their access using guest purchases sent to the same address. Render a verification
217
+ notice for unverified customers in the course area without revealing guest purchases.
218
+
219
+ Show customer cancellation only for an owned `PENDING` and `UNPAID` order.
220
+ The backend checks both states while holding the order lock; payment can change
221
+ after the page loads, so keep a visible error and refresh the order after rejection.
222
+ Cancellation restores the actual remaining stock deduction once. Warehouse
223
+ allocation identifiers are internal and must never be rendered by a template.
224
+
225
+ ### Canonical discovery URLs
226
+
227
+ `catalog.getSitemap(locale?)` follows canonical variant indexing and bound-domain
228
+ product selection. Its entries and `ProductDetail.seo` expose optional
229
+ `localizedSlugs` in 1.20, mapping enabled languages to actual canonical slugs.
230
+ Use those for hreflang and language links; omit unknown translations instead
231
+ of inventing them. Crawler clients must be sessionless. In Next metadata routes,
232
+ call `connection()` before dynamic SDK fetches and verify a production build.
233
+
234
+ ### Catalog availability and price privacy
235
+
236
+ A failed price entitlement lookup returns HTTP 503 with `be.storefront.pricingUnavailable`; unrestricted guest pricing is never a fallback. With `throwOnAvailabilityError: true`, catch known SDK availability exceptions only where an explicit server-rendered error and retry replace the failed content. A `{data, error}` check alone cannot handle that exception path. Never treat an outage as zero reviews, zero products, a free offer, or a 404.
237
+
238
+ ### Complete category filters
239
+
240
+ `catalog.getCategoryProducts(slug, query)` shares the full `ProductsQuery` serializer with `getProducts`. Price bounds retain zero, boolean filters retain false, arrays use repeated parameters and public parameter/facet selections use JSON. Category, main-list and featured availability follow the same published-variant and stock-mode rules in the backend.
241
+
242
+ ### Bundle offers and galleries (2.0, unreleased)
243
+
244
+ `catalog.getBundles({locale, currency, country})` and `getBundle(slug, options)`
245
+ return explicit `priceHidden`, `isPurchasable` and `unavailableReason` alongside
246
+ nullable prices and savings. Never render a null price as zero. Honor
247
+ `quantityRules.minimum`, `step` and nullable `maximum` for additional complete
248
+ sets in the current visitor basket. The server accounts for component steps,
249
+ ordinary rows, other bundles, shared stock and merchant limits. Bundle list/detail
250
+ requests carry the cart session and customer, return private `no-store` data, and
251
+ must not enter shared caches. Hidden stock does not expose a numerical ceiling. React bundle
252
+ hooks accept the same context plus server `initialData` and separate query caches
253
+ by that context. They wait for session restoration; cart and auth hooks refresh
254
+ their ranges after basket or identity changes. Direct core bundle mutations need
255
+ cart refresh plus cancellation/invalidation of both bundle query prefixes.
256
+ API errors require a retry state; they are not an empty catalog.
257
+
258
+ Merge a product's listing `images` with its shared `media` and deduplicate safe
259
+ URLs. A shared video must not hide additional listing photos. Render the image
260
+ links in the first HTML, then enhance thumbnail selection and native video.
261
+
262
+ Bundle checkout previews resolve the current explicit currency offer and component
263
+ rules. Submit the preview token with the confirmed order; handle `checkoutChanged`
264
+ by showing a new preview. Pending orders hold the bundle quota, terminal
265
+ cancellation/refund releases it, and reopening must claim it again. Stock modes
266
+ ALWAYS_AVAILABLE and MADE_TO_ORDER override saved tracked-stock limits throughout
267
+ cart, checkout and order transitions, while retaining exact inventory movements.
268
+
269
+ Cart bundle lines return the **current** offer in the legacy-named
270
+ `bundlePriceSnapshot` field. Stored cart and order snapshots are unchanged by a
271
+ read. Show `priceChanged` and use `quantityControls.decreaseTo` / `increaseTo`
272
+ for exact resulting whole-set quantities; null disables that direction. Keep
273
+ server validation errors next to the row. Older servers can omit these controls. Native
274
+ server-bound quantity/remove forms work before hydration. Bundle components keep
275
+ their own tax rates and their allocated price participates in coupon targeting;
276
+ cart reads recheck coupon eligibility after merchant or cart changes.
277
+
278
+ Version 2 changes bundle catalog prices and `CartBundleLine.bundlePriceSnapshot`
279
+ to nullable values. Update consumers before upgrading: null is unavailable,
280
+ never a free offer. An invalid bundle stays in the cart with `isPurchasable: false`
281
+ and an `unavailableReason`; keep its remove control. `QUANTITY_UNAVAILABLE` may
282
+ be repairable by changing the quantity. When `cart.totalsAvailable === false`,
283
+ hide monetary totals and disable checkout in both cart and mini cart. Do not
284
+ interpret the remaining numeric summary fields as a payable quote. The server
285
+ rechecks component publication, sale windows, quantity, stock and domain selection
286
+ before a bundle mutation. The SDK retains the session returned when an anonymous
287
+ visitor first adds a bundle, so subsequent reads address the same cart.
288
+
289
+ ### Retained product rows (2.0, unreleased)
290
+
291
+ SDK 2 sends `X-Behio-Cart-Contract: 2` on every cart request. This opts into
292
+ nullable current prices. On the same v1 route, clients without this header
293
+ retain numeric, same-currency stored price snapshots when the current offer
294
+ disappears. That compatibility projection is not purchase authorization:
295
+ preview and checkout always validate the current offer. An old client still
296
+ needs upgrading to display the new availability and repair controls. Snapshots
297
+ never bypass hidden-price authentication or relabel a foreign currency.
298
+
299
+ A product row also reports `isPurchasable` and `unavailableReason`. Its unit,
300
+ line and tax amounts, plus `product.currentPrice`, are nullable when there is
301
+ no current currency price. Do not revive an old snapshot or show null as zero.
302
+ Keep the row removable; `cart.totalsAvailable` applies to products and bundles.
303
+
304
+ Prefer `item.quantityControls.decreaseTo` and `increaseTo` for cart steppers.
305
+ A null target disables that direction. These targets account for units of the
306
+ same product inside bundles, other listings sharing its stock, merchant minima,
307
+ step multiples and maximums. They can jump directly to a valid repair after a
308
+ merchant edit. Existing fractional units keep their fraction when no merchant
309
+ step is configured. The server validates the resulting basket before writing;
310
+ show returned errors next to the native form and reread the authoritative cart.
311
+
312
+ Domain-bound availability is preserved in currency, destination, code, merge,
313
+ and removal responses. Analytics must omit unknown amounts and must not emit a
314
+ payable cart value when `totalsAvailable` is false.
@@ -181,6 +181,7 @@ var BehioStorefront = class {
181
181
  this.shopDomain = config.shopDomain;
182
182
  this.defaultLocale = config.locale;
183
183
  this.defaultCurrency = config.currency;
184
+ this.setCountry(config.country);
184
185
  this.fetchFn = config.fetch || globalThis.fetch.bind(globalThis);
185
186
  this.timeout = config.timeout ?? 3e4;
186
187
  this.retries = config.retries ?? 1;
@@ -342,6 +343,14 @@ var BehioStorefront = class {
342
343
  getCurrency() {
343
344
  return this.defaultCurrency;
344
345
  }
346
+ /** Set the catalog's delivery country. Use cart.setDestination separately for the cart. */
347
+ setCountry(country) {
348
+ const normalized = country?.trim().toUpperCase();
349
+ this.defaultCountry = normalized && /^[A-Z]{2}$/.test(normalized) ? normalized : void 0;
350
+ }
351
+ getCountry() {
352
+ return this.defaultCountry;
353
+ }
345
354
  /** Set the default locale sent on every catalog request (per-call wins). */
346
355
  setLocale(locale) {
347
356
  this.defaultLocale = locale || void 0;
@@ -497,12 +506,16 @@ var BehioStorefront = class {
497
506
  if (this.defaultCurrency && !params.has("currency")) {
498
507
  params.set("currency", this.defaultCurrency);
499
508
  }
509
+ if (this.defaultCountry && path.startsWith("/catalog/") && !params.has("country")) {
510
+ params.set("country", this.defaultCountry);
511
+ }
500
512
  const qs = params.toString();
501
513
  const url = `${this.baseUrl}/storefront/v1${path}${qs ? `?${qs}` : ""}`;
502
514
  const headers = {
503
515
  "X-Api-Key": this.apiKey,
504
516
  "Content-Type": "application/json"
505
517
  };
518
+ if (path === "/cart" || path.startsWith("/cart/")) headers["X-Behio-Cart-Contract"] = "2";
506
519
  if (this.shopDomain) {
507
520
  headers["X-Shop-Domain"] = this.shopDomain;
508
521
  }
@@ -629,42 +642,46 @@ var BehioStorefront = class {
629
642
  throw new BehioNetworkError("Request failed after retries");
630
643
  }
631
644
  };
645
+ function catalogProductsQuery(query) {
646
+ const q = {};
647
+ if (query) {
648
+ if (query.page !== void 0) q.page = query.page;
649
+ if (query.limit !== void 0) q.limit = query.limit;
650
+ if (query.category) q.category = query.category;
651
+ if (query.label) q.label = query.label;
652
+ if (query.priceMin !== void 0) q.priceMin = query.priceMin;
653
+ if (query.priceMax !== void 0) q.priceMax = query.priceMax;
654
+ if (query.currency) q.currency = query.currency;
655
+ if (query.country) q.country = query.country;
656
+ if (query.locale) q.locale = query.locale;
657
+ if (query.sort) q.sort = query.sort;
658
+ if (query.inStock !== void 0) q.inStock = query.inStock;
659
+ if (query.ratingMin !== void 0) q.ratingMin = query.ratingMin;
660
+ if (query.search) q.search = query.search;
661
+ if (query.parameters) q.parameters = JSON.stringify(query.parameters);
662
+ if (query.facets) q.facets = JSON.stringify(query.facets);
663
+ if (query.ids && query.ids.length > 0) q.ids = query.ids;
664
+ if (query.slugs && query.slugs.length > 0) q.slugs = query.slugs;
665
+ if (query.labels && query.labels.length > 0) q.labels = query.labels;
666
+ if (query.categories && query.categories.length > 0)
667
+ q.categories = query.categories;
668
+ if (query.excludeIds && query.excludeIds.length > 0)
669
+ q.excludeIds = query.excludeIds;
670
+ if (query.excludeCategories && query.excludeCategories.length > 0)
671
+ q.excludeCategories = query.excludeCategories;
672
+ if (query.hasDiscount !== void 0) q.hasDiscount = query.hasDiscount;
673
+ if (query.isFeatured !== void 0) q.isFeatured = query.isFeatured;
674
+ if (query.createdAfter !== void 0) q.createdAfter = query.createdAfter;
675
+ }
676
+ return q;
677
+ }
632
678
  var CatalogModule = class {
633
679
  constructor(client) {
634
680
  this.client = client;
635
681
  }
636
682
  /** List products with filtering, pagination, search */
637
683
  async getProducts(query) {
638
- const q = {};
639
- if (query) {
640
- if (query.page) q.page = query.page;
641
- if (query.limit) q.limit = query.limit;
642
- if (query.category) q.category = query.category;
643
- if (query.label) q.label = query.label;
644
- if (query.priceMin) q.priceMin = query.priceMin;
645
- if (query.priceMax) q.priceMax = query.priceMax;
646
- if (query.currency) q.currency = query.currency;
647
- if (query.country) q.country = query.country;
648
- if (query.locale) q.locale = query.locale;
649
- if (query.sort) q.sort = query.sort;
650
- if (query.inStock !== void 0) q.inStock = query.inStock;
651
- if (query.ratingMin !== void 0) q.ratingMin = query.ratingMin;
652
- if (query.search) q.search = query.search;
653
- if (query.parameters) q.parameters = JSON.stringify(query.parameters);
654
- if (query.facets) q.facets = JSON.stringify(query.facets);
655
- if (query.ids && query.ids.length > 0) q.ids = query.ids;
656
- if (query.slugs && query.slugs.length > 0) q.slugs = query.slugs;
657
- if (query.labels && query.labels.length > 0) q.labels = query.labels;
658
- if (query.categories && query.categories.length > 0)
659
- q.categories = query.categories;
660
- if (query.excludeIds && query.excludeIds.length > 0)
661
- q.excludeIds = query.excludeIds;
662
- if (query.excludeCategories && query.excludeCategories.length > 0)
663
- q.excludeCategories = query.excludeCategories;
664
- if (query.hasDiscount !== void 0) q.hasDiscount = query.hasDiscount;
665
- if (query.isFeatured !== void 0) q.isFeatured = query.isFeatured;
666
- if (query.createdAfter !== void 0) q.createdAfter = query.createdAfter;
667
- }
684
+ const q = catalogProductsQuery(query);
668
685
  return this.client.request(
669
686
  "GET",
670
687
  "/catalog/products",
@@ -706,14 +723,7 @@ var CatalogModule = class {
706
723
  }
707
724
  /** Get products in a category */
708
725
  async getCategoryProducts(slug, query) {
709
- const q = {};
710
- if (query) {
711
- if (query.page) q.page = query.page;
712
- if (query.limit) q.limit = query.limit;
713
- if (query.sort) q.sort = query.sort;
714
- if (query.locale) q.locale = query.locale;
715
- if (query.currency) q.currency = query.currency;
716
- }
726
+ const q = catalogProductsQuery(query);
717
727
  return this.client.request(
718
728
  "GET",
719
729
  `/catalog/categories/${slug}/products`,
@@ -747,7 +757,7 @@ var CatalogModule = class {
747
757
  "GET",
748
758
  "/catalog/featured",
749
759
  {
750
- query: { locale: options?.locale, currency: options?.currency }
760
+ query: { locale: options?.locale, currency: options?.currency, country: options?.country }
751
761
  }
752
762
  );
753
763
  }
@@ -805,9 +815,10 @@ var CatalogModule = class {
805
815
  if (query) {
806
816
  if (query.category) q.category = query.category;
807
817
  if (query.label) q.label = query.label;
808
- if (query.priceMin) q.priceMin = query.priceMin;
809
- if (query.priceMax) q.priceMax = query.priceMax;
818
+ if (query.priceMin !== void 0) q.priceMin = query.priceMin;
819
+ if (query.priceMax !== void 0) q.priceMax = query.priceMax;
810
820
  if (query.currency) q.currency = query.currency;
821
+ if (query.country) q.country = query.country;
811
822
  if (query.locale) q.locale = query.locale;
812
823
  if (query.inStock !== void 0) q.inStock = query.inStock;
813
824
  if (query.ratingMin !== void 0) q.ratingMin = query.ratingMin;
@@ -829,12 +840,12 @@ var CatalogModule = class {
829
840
  return this.getProducts({ search: query, ...options });
830
841
  }
831
842
  /** List all active bundles */
832
- async getBundles() {
833
- return this.client.request("GET", "/catalog/bundles");
843
+ async getBundles(options) {
844
+ return this.client.request("GET", "/catalog/bundles", { query: { ...options } });
834
845
  }
835
846
  /** Get a single bundle by slug */
836
- async getBundle(slug) {
837
- return this.client.request("GET", `/catalog/bundles/${slug}`);
847
+ async getBundle(slug, options) {
848
+ return this.client.request("GET", `/catalog/bundles/${encodeURIComponent(slug)}`, { query: { ...options } });
838
849
  }
839
850
  /**
840
851
  * One product group ("collection") by slug with its products as standard
@@ -847,7 +858,7 @@ var CatalogModule = class {
847
858
  "GET",
848
859
  `/catalog/product-groups/${encodeURIComponent(slug)}`,
849
860
  {
850
- query: { locale: options?.locale, currency: options?.currency }
861
+ query: { locale: options?.locale, currency: options?.currency, country: options?.country }
851
862
  }
852
863
  );
853
864
  }
@@ -862,7 +873,7 @@ var CatalogModule = class {
862
873
  return this.client.request(
863
874
  "GET",
864
875
  `/catalog/products/${encodeURIComponent(productSlug)}/cross-sell`,
865
- { query: { locale: options?.locale, currency: options?.currency } }
876
+ { query: { locale: options?.locale, currency: options?.currency, country: options?.country } }
866
877
  );
867
878
  }
868
879
  /** Active promotions applicable to a product (with countdown end time) */
@@ -1070,6 +1081,7 @@ var CartModule = class {
1070
1081
  body: { currency }
1071
1082
  });
1072
1083
  if (res.error) return res;
1084
+ if (res.data.sessionToken) this.client.setCartSession(res.data.sessionToken);
1073
1085
  this.client.emit("cart:updated", res.data);
1074
1086
  return res;
1075
1087
  }
@@ -1090,6 +1102,7 @@ var CartModule = class {
1090
1102
  body: input
1091
1103
  });
1092
1104
  if (res.error) return res;
1105
+ if (res.data.sessionToken) this.client.setCartSession(res.data.sessionToken);
1093
1106
  this.client.emit("cart:updated", res.data);
1094
1107
  return res;
1095
1108
  }
@@ -1174,14 +1187,15 @@ var CartModule = class {
1174
1187
  body
1175
1188
  });
1176
1189
  if (res.error) return res;
1190
+ if (res.data.sessionToken) this.client.setCartSession(res.data.sessionToken);
1177
1191
  this.client.emit("cart:updated", res.data);
1178
1192
  return res;
1179
1193
  }
1180
- /** Update quantity of a bundle already in the cart */
1181
- async updateBundleQuantity(bundleId, quantity) {
1194
+ /** Update by CartBundleLine.id; legacy catalog bundle IDs are accepted by the API */
1195
+ async updateBundleQuantity(lineId, quantity) {
1182
1196
  const res = await this.client.request(
1183
1197
  "PATCH",
1184
- `/cart/bundles/${bundleId}`,
1198
+ `/cart/bundles/${lineId}`,
1185
1199
  {
1186
1200
  body: { quantity }
1187
1201
  }
@@ -1190,11 +1204,11 @@ var CartModule = class {
1190
1204
  this.client.emit("cart:updated", res.data);
1191
1205
  return res;
1192
1206
  }
1193
- /** Remove a bundle from the cart */
1194
- async removeBundle(bundleId) {
1207
+ /** Remove by CartBundleLine.id; scoped to the current visitor cart */
1208
+ async removeBundle(lineId) {
1195
1209
  const res = await this.client.request(
1196
1210
  "DELETE",
1197
- `/cart/bundles/${bundleId}`
1211
+ `/cart/bundles/${lineId}`
1198
1212
  );
1199
1213
  if (res.error) return res;
1200
1214
  this.client.emit("cart:updated", res.data);
@@ -1228,6 +1242,12 @@ var CheckoutModule = class {
1228
1242
  constructor(client) {
1229
1243
  this.client = client;
1230
1244
  }
1245
+ /** Recalculate the current cart including shipping, fees, benefits and rounding.
1246
+ * No order, stock claim, payment or gift-card redemption is created. Required
1247
+ * legal consents are enforced only on createOrder, not while quoting. */
1248
+ async preview(input) {
1249
+ return this.client.request("POST", "/checkout/preview", { body: input });
1250
+ }
1231
1251
  /** Create order from cart */
1232
1252
  async createOrder(input) {
1233
1253
  const res = await this.client.request("POST", "/checkout", {