brainerce 1.47.1 → 1.48.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
@@ -32,29 +32,30 @@ yarn add brainerce
32
32
 
33
33
  Every Brainerce storefront must include **all mandatory features** below. Features auto-hide when the underlying capability is disabled, so build them all anyway — they'll appear the moment the store owner enables them.
34
34
 
35
- | Feature | SDK entry point | Mandatory |
36
- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----------- |
37
- | Product list with search, filter, pagination | `client.getProducts()`, `client.getSearchSuggestions(query)` | ✅ |
38
- | Product detail with variant picker, stock, price | `client.getProductBySlug()` + helpers | ✅ |
39
- | Buyer customization fields (engraving, uploads, select) | `product.customizationFields`, `client.uploadCustomizationFile()` | ✅ |
40
- | Cart (add, update, remove, coupon, totals) | `client.addToCart()`, `getCartTotals(cart)` | ✅ |
41
- | Inventory reservation countdown | Cart expiry timestamp from `client.getCart()` | ✅ |
42
- | Full checkout end-to-end with payment | `setShippingAddress → selectShippingMethod → getPaymentProviders → pay → handlePaymentSuccess → waitForOrder` | ✅ |
43
- | Order confirmation (clear cart + wait for real order) | `client.handlePaymentSuccess()`, `client.waitForOrder()` | ✅ |
44
- | Register + email verification flow | `client.registerCustomer()`, `client.verifyEmail()` | ✅ |
45
- | Login + verification branch | `client.loginCustomer()` | ✅ |
46
- | Forgot / reset password | `client.forgotPassword()`, `client.resetPassword()` | ✅ |
47
- | OAuth sign-in buttons + callback handler | `client.getAvailableOAuthProviders()` | ✅ |
48
- | Account area (profile + order history) | `client.getMyProfile()`, `client.getMyOrders()` | ✅ |
49
- | Loyalty & rewards (points balance + tiers + redeem) | `client.getLoyaltyStatus()`, `client.getAvailableRewards()`, `client.getRecommendedReward()`, `client.redeemLoyaltyReward(id)`, `client.reportSocialShare()` | conditional |
50
- | Loyalty paid membership (premium subscription) | `client.getMembershipPlans()`, `client.getMySavedPaymentMethods()`, `client.subscribeToMembership(params)`, `client.cancelMembership()` | conditional |
51
- | Global header: cart count + search autocomplete | `client.getCart()`, `client.getSearchSuggestions(query)` | |
52
- | Discount banners + product badges | `client.getDiscountBanners()`, `client.getProductDiscountBadge(productId)` | ✅ |
53
- | Product reviews on PDP + JSON-LD aggregateRating | `client.listProductReviews(id)`, `client.submitProductReview(id, …)` | ✅ |
54
- | Site chrome (header + footer + announcement bar) | `client.content.header.get()`, `client.content.footer.get()`, `client.content.announcement.list()` | ✅ |
55
- | FAQ page | `client.content.faq.get('main', locale)` | conditional |
56
- | Static pages catch-all (`/pages/[slug]`) | `client.content.page.getBySlug(slug, locale)` | conditional |
57
- | Multi-language + RTL (when i18n enabled) | `client.setLocale()`, `client.getStoreDirection(locale)` | conditional |
35
+ | Feature | SDK entry point | Mandatory |
36
+ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- |
37
+ | Product list with search, filter, pagination | `client.getProducts()`, `client.getSearchSuggestions(query)` | ✅ |
38
+ | Product detail with variant picker, stock, price | `client.getProductBySlug()` + helpers | ✅ |
39
+ | Buyer customization fields (engraving, uploads, select) | `product.customizationFields`, `client.uploadCustomizationFile()` | ✅ |
40
+ | Cart (add, update, remove, coupon, totals) | `client.addToCart()`, `getCartTotals(cart)` | ✅ |
41
+ | Inventory reservation countdown | Cart expiry timestamp from `client.getCart()` | ✅ |
42
+ | Full checkout end-to-end with payment | `setShippingAddress → selectShippingMethod → getPaymentProviders → pay → handlePaymentSuccess → waitForOrder` | ✅ |
43
+ | Order confirmation (clear cart + wait for real order) | `client.handlePaymentSuccess()`, `client.waitForOrder()` | ✅ |
44
+ | Register + email verification flow | `client.registerCustomer()`, `client.verifyEmail()` | ✅ |
45
+ | Login + verification branch | `client.loginCustomer()` | ✅ |
46
+ | Forgot / reset password | `client.forgotPassword()`, `client.resetPassword()` | ✅ |
47
+ | OAuth sign-in buttons + callback handler | `client.getAvailableOAuthProviders()` | ✅ |
48
+ | Account area (profile + order history) | `client.getMyProfile()`, `client.getMyOrders()` | ✅ |
49
+ | Loyalty & rewards (points balance + tiers + redeem) | `client.getLoyaltyStatus()`, `client.getAvailableRewards()`, `client.getRecommendedReward()`, `client.redeemLoyaltyReward(id)`, `client.reportSocialShare()` | conditional |
50
+ | Loyalty paid membership (premium subscription) | `client.getMembershipPlans()`, `client.getMySavedPaymentMethods()`, `client.subscribeToMembership(params)`, `client.cancelMembership()` | conditional |
51
+ | Embeddable loyalty widget (points + rewards on ANY site) | `client.getLoyaltyWidgetSession()` | conditional |
52
+ | Global header: cart count + search autocomplete | `client.getCart()`, `client.getSearchSuggestions(query)` | ✅ |
53
+ | Discount banners + product badges | `client.getDiscountBanners()`, `client.getProductDiscountBadge(productId)` | ✅ |
54
+ | Product reviews on PDP + JSON-LD aggregateRating | `client.listProductReviews(id)`, `client.submitProductReview(id, )` | ✅ |
55
+ | Site chrome (header + footer + announcement bar) | `client.content.header.get()`, `client.content.footer.get()`, `client.content.announcement.list()` | |
56
+ | FAQ page | `client.content.faq.get('main', locale)` | conditional |
57
+ | Static pages catch-all (`/pages/[slug]`) | `client.content.page.getBySlug(slug, locale)` | conditional |
58
+ | Multi-language + RTL (when i18n enabled) | `client.setLocale()`, `client.getStoreDirection(locale)` | conditional |
58
59
 
59
60
  ---
60
61
 
@@ -271,7 +272,7 @@ The SDK exports these utility functions for common UI tasks:
271
272
  | `buildArticleJsonLd(post, opts)` | schema.org Article JSON-LD for blog posts | See SEO section |
272
273
  | `buildOrganizationJsonLd(store, opts)` | schema.org Organization for the homepage | See SEO section |
273
274
  | `buildBreadcrumbJsonLd(items)` | schema.org BreadcrumbList | See SEO section |
274
- | `jsonLdScriptProps(data)` | XSS-safe `<script type="application/ld+json">` props | `<script {...jsonLdScriptProps(data)} />` |
275
+ | `jsonLdScriptProps(data)` | XSS-safe `<script type="application/ld+json">` props | `<script {...jsonLdScriptProps(data)} />` |
275
276
  | `getBlogSitemapEntries(client, opts)` | Paginate published posts into sitemap entries | See SEO section |
276
277
 
277
278
  ```typescript
@@ -464,15 +465,16 @@ return <div dangerouslySetInnerHTML={{ __html: safeHtml }} className="prose" />;
464
465
 
465
466
  ### SEO — JSON-LD builders, sitemap helper, IndexNow key, llms.txt
466
467
 
467
- The SDK ships schema.org builders that encode Google's structured-data rules (aggregateRating gated on `reviewCount > 0`, AggregateOffer for VARIABLE products, XSS-safe serialization). Prefer them over hand-rolled JSON-LD:
468
+ The SDK ships schema.org builders that encode Google's structured-data rules (aggregateRating gated on `reviewCount > 0`, AggregateOffer for VARIABLE products, XSS-safe serialization). `buildProductJsonLd`'s Offer also always includes `itemCondition` (hardcoded `NewCondition` — first-party new-goods catalog), `priceValidUntil` when the product has an active sale-price window (`salePriceEndsAt`), and `shippingDetails` when you pass `shipping` (real flat-rate/free zones from `storeInfo.shipping` — omitted entirely, never fabricated, if you don't pass it). Prefer these builders over hand-rolled JSON-LD:
468
469
 
469
470
  ```tsx
470
471
  import {
471
- buildProductJsonLd, // single-product pages ONLY (never listing pages)
472
- buildArticleJsonLd, // blog post pages
473
- buildOrganizationJsonLd, // homepage
472
+ buildProductJsonLd, // single-product pages ONLY (never listing pages)
473
+ buildArticleJsonLd, // blog post pages
474
+ buildOrganizationJsonLd, // homepage
475
+ buildCollectionPageJsonLd, // category landing pages
474
476
  buildBreadcrumbJsonLd,
475
- jsonLdScriptProps, // XSS-safe <script> props
477
+ jsonLdScriptProps, // XSS-safe <script> props
476
478
  } from 'brainerce';
477
479
 
478
480
  // Blog article page
@@ -487,6 +489,7 @@ import {
487
489
  siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
488
490
  path: `/products/${product.slug}`,
489
491
  currency: storeInfo.currency,
492
+ shipping: storeInfo.shipping, // optional — adds shippingDetails when present
490
493
  }))} />
491
494
  ```
492
495
 
@@ -862,6 +865,26 @@ import { getCartTotals } from 'brainerce';
862
865
  const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
863
866
  ```
864
867
 
868
+ ### Detecting a Silent Session Cart Reset
869
+
870
+ If a guest's stored session cart can no longer be resolved as-is — the fetch
871
+ fails, or the cart was found but is no longer `ACTIVE` (e.g. a prior checkout
872
+ on it already completed) — `smartAddToCart()` / `smartGetCart()` /
873
+ `smartUpdateCartItem()` transparently start a fresh empty cart so the call
874
+ still succeeds. Pass `onCartReset` to the constructor to find out when this
875
+ happens, so you can tell the shopper their cart expired instead of them just
876
+ seeing it empty out:
877
+
878
+ ```typescript
879
+ const client = new BrainerceClient({
880
+ salesChannelId: 'vc_abc123...',
881
+ onCartReset: ({ previousCartId, reason }) => {
882
+ // reason: 'not_found' (fetch failed) | 'not_active' (cart no longer ACTIVE)
883
+ toast.warn('Your cart session expired — please re-add your items.');
884
+ },
885
+ });
886
+ ```
887
+
865
888
  ### On Login — Merge Guest Cart
866
889
 
867
890
  ```typescript
@@ -1536,17 +1559,19 @@ interface Product {
1536
1559
  description?: string | null;
1537
1560
  descriptionFormat?: 'text' | 'html' | 'markdown'; // Format of description content
1538
1561
  sku: string;
1539
- basePrice: number;
1540
- salePrice?: number | null;
1562
+ basePrice: string; // Decimal as string — use parseFloat() for calculations
1563
+ salePrice?: string | null;
1564
+ salePriceStartsAt?: string | null; // ISO 8601 — sale-price effective window start
1565
+ salePriceEndsAt?: string | null; // ISO 8601 — sale-price window end; feeds buildProductJsonLd's priceValidUntil
1541
1566
  priceMin?: string | null; // Lowest variant price (VARIABLE products only)
1542
1567
  priceMax?: string | null; // Highest variant price (VARIABLE products only)
1543
1568
  priceVaries?: boolean; // true when range should be shown ("₪49 – ₪199")
1544
- status: 'active' | 'draft';
1569
+ status: string; // e.g. "active" | "draft"
1545
1570
  type: 'SIMPLE' | 'VARIABLE';
1546
1571
  images?: ProductImage[];
1547
1572
  inventory?: InventoryInfo | null;
1548
1573
  variants?: ProductVariant[];
1549
- categories?: string[];
1574
+ categories?: Array<{ id: string; name: string; slug?: string | null }>; // NOT string[] — use slug to link to /category/{slug}
1550
1575
  tags?: string[];
1551
1576
  createdAt: string;
1552
1577
  updatedAt: string;
@@ -3057,6 +3082,13 @@ const profile = await client.getMyProfile();
3057
3082
  console.log(profile.firstName);
3058
3083
  console.log(profile.email);
3059
3084
  console.log(profile.addresses);
3085
+
3086
+ // profile.role is a free-form segment the merchant sets from the dashboard
3087
+ // (e.g. "wholesale", "vip") — not customer-editable. Use it to gate custom
3088
+ // storefront features/UI: wholesale pricing, a VIP section, etc.
3089
+ if (profile.role === 'wholesale') {
3090
+ // show wholesale pricing / a bulk-order UI
3091
+ }
3060
3092
  ```
3061
3093
 
3062
3094
  #### Get Customer Orders
@@ -3070,9 +3102,9 @@ const { data: orders, meta } = await client.getMyOrders({
3070
3102
 
3071
3103
  #### Loyalty & Rewards
3072
3104
 
3073
- Storefront-mode only (requires `storeId` + `customerToken`). Let logged-in
3074
- customers check their points balance, enroll, and redeem rewards for one-time
3075
- coupons that apply at checkout.
3105
+ Storefront or vibe-coded mode (requires `storeId` or `salesChannelId` +
3106
+ `customerToken`). Let logged-in customers check their points balance, enroll,
3107
+ and redeem rewards for one-time coupons that apply at checkout.
3076
3108
 
3077
3109
  ```typescript
3078
3110
  // Current status — points balance + program display config + tier progress +
@@ -3149,8 +3181,9 @@ platform emails a one-time gift coupon ahead of their birthday automatically
3149
3181
 
3150
3182
  Stores can offer a paid "premium membership" inside the loyalty program — a
3151
3183
  recurring charge (default every 30 days) that grants a points multiplier and
3152
- other perks. Storefront-mode only, requires `customerToken`. The customer must
3153
- first have a saved card (vault one by checking out with `saveCard: true`).
3184
+ other perks. Storefront or vibe-coded mode, requires `customerToken`. The
3185
+ customer must first have a saved card (vault one by checking out with
3186
+ `saveCard: true`).
3154
3187
 
3155
3188
  ```typescript
3156
3189
  // 1. Plans the store offers (empty if none / program not active).
@@ -3182,6 +3215,26 @@ const cancelled = await client.cancelMembership();
3182
3215
  // pauses the multiplier until the charge clears.
3183
3216
  ```
3184
3217
 
3218
+ #### Embeddable Loyalty Widget
3219
+
3220
+ Drop the loyalty program into ANY website — not just your SDK-connected
3221
+ storefront. Mint a short-lived widget session (never exposes the real
3222
+ `customerToken` to the embedding page) and point an `<iframe>` at it. The
3223
+ merchant enables this per-domain in the dashboard (Loyalty → Settings →
3224
+ Embeddable widget) before it will render anywhere.
3225
+
3226
+ ```typescript
3227
+ client.setCustomerToken(auth.token);
3228
+
3229
+ const { embedUrl } = await client.getLoyaltyWidgetSession();
3230
+
3231
+ // <iframe src={embedUrl} width="360" height="420" style={{ border: 0 }} />
3232
+ ```
3233
+
3234
+ `embedUrl` expires in ~15 minutes — re-call `getLoyaltyWidgetSession()` before
3235
+ that (e.g. on page load) rather than caching it long-term. Storefront or
3236
+ vibe-coded mode, requires `customerToken`.
3237
+
3185
3238
  #### Auth Response Type
3186
3239
 
3187
3240
  ```typescript
package/dist/index.d.mts CHANGED
@@ -76,6 +76,31 @@ interface BrainerceClientOptions {
76
76
  statusCode: number;
77
77
  path?: string;
78
78
  }) => void;
79
+ /**
80
+ * Callback fired when the SDK silently resets the guest session cart because
81
+ * the previously-stored cart could no longer be resolved as-is — either the
82
+ * fetch failed (network error, 404 — cart deleted/expired) or the cart was
83
+ * found but is no longer `ACTIVE` (e.g. a prior checkout on it already
84
+ * completed or the cart was abandoned/merged). In both cases the SDK
85
+ * transparently creates a fresh empty cart so `smartAddToCart()` /
86
+ * `smartGetCart()` keep working — this callback is your only signal that it
87
+ * happened, so the storefront can tell the shopper their cart expired
88
+ * instead of them just seeing it silently empty out.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const client = new BrainerceClient({
93
+ * salesChannelId: 'vc_abc123...',
94
+ * onCartReset: ({ previousCartId, reason }) => {
95
+ * toast.warn('Your cart session expired — please re-add your items.');
96
+ * },
97
+ * });
98
+ * ```
99
+ */
100
+ onCartReset?: (info: {
101
+ previousCartId: string;
102
+ reason: 'not_found' | 'not_active';
103
+ }) => void;
79
104
  /**
80
105
  * Origin header to send with requests.
81
106
  * Browsers add this automatically, but Node.js environments (SSR, scripts, npx)
@@ -204,6 +229,26 @@ interface StoreInfo {
204
229
  seo?: {
205
230
  indexNowKey: string | null;
206
231
  };
232
+ /**
233
+ * Real merchant-configured shipping rates (sales-channel mode only) —
234
+ * flat-rate/free zones only, each with a single unconditional price.
235
+ * Weight/price-tiered and local-pickup rates are excluded because their
236
+ * cost depends on cart contents, so there's no single number to declare.
237
+ * Feeds Product JSON-LD `shippingDetails` — pass as `buildProductJsonLd(product, { ..., shipping: storeInfo.shipping })`.
238
+ */
239
+ shipping?: ShippingSummaryEntry[];
240
+ }
241
+ /** One flat-rate/free shipping zone, as exposed by `StoreInfo.shipping`. */
242
+ interface ShippingSummaryEntry {
243
+ /** ISO 3166-1 alpha-2 country codes this rate applies to. */
244
+ countries: string[];
245
+ rateType: 'FLAT_RATE' | 'FREE';
246
+ /** Shipping cost in the store's currency. `0` for FREE, `null` if a FLAT_RATE has no configured amount. */
247
+ amount: number | null;
248
+ minDeliveryDays: number | null;
249
+ maxDeliveryDays: number | null;
250
+ /** Order-processing time in business days before the item ships. */
251
+ handlingTime: number | null;
207
252
  }
208
253
  /** Multi-language configuration exposed to the storefront */
209
254
  interface I18nSettings {
@@ -254,6 +299,8 @@ interface CustomerProfile {
254
299
  phone?: string;
255
300
  emailVerified: boolean;
256
301
  acceptsMarketing: boolean;
302
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. Admin-set only, never customer-editable. */
303
+ role?: string;
257
304
  addresses: CustomerAddress[];
258
305
  createdAt: string;
259
306
  updatedAt: string;
@@ -497,6 +544,10 @@ interface Product {
497
544
  * `SIMPLE` products it is the product's own stored sale price.
498
545
  */
499
546
  salePrice?: string | null;
547
+ /** ISO 8601 — start of the sale-price effective window. `null` when unset (sale has no window). */
548
+ salePriceStartsAt?: string | null;
549
+ /** ISO 8601 — end of the sale-price effective window. Feeds Product JSON-LD `priceValidUntil`. `null` when unset. */
550
+ salePriceEndsAt?: string | null;
500
551
  /** Cost price as string. Use parseFloat() for calculations. */
501
552
  costPrice?: string | null;
502
553
  /** Lowest effective variant price (VARIABLE products only). String Decimal, e.g. "19.99". */
@@ -526,13 +577,15 @@ interface Product {
526
577
  inventory?: InventoryInfo | null;
527
578
  variants?: ProductVariant[];
528
579
  /**
529
- * Categories as objects with `id` and `name`.
530
- * NOT string[] - each category is `{ id: string; name: string }`.
531
- * Access: `product.categories?.map(cat => cat.name)`
580
+ * Categories as objects with `id`, `name`, and `slug`.
581
+ * NOT string[] - each category is `{ id: string; name: string; slug?: string | null }`.
582
+ * Access: `product.categories?.map(cat => cat.name)`. Use `slug` to link to
583
+ * that category's `/category/{slug}` landing page.
532
584
  */
533
585
  categories?: Array<{
534
586
  id: string;
535
587
  name: string;
588
+ slug?: string | null;
536
589
  }>;
537
590
  /** Brands as objects with id and name */
538
591
  brands?: Array<{
@@ -704,6 +757,10 @@ interface ProductVariant {
704
757
  price?: string | null;
705
758
  /** Variant sale price as string. Use parseFloat() for calculations. */
706
759
  salePrice?: string | null;
760
+ /** Variant unit cost (COGS) override as string — falls back to the product
761
+ * costPrice in margin analytics. Admin (apiKey) reads only; public
762
+ * storefront responses never include it. */
763
+ costPrice?: string | null;
707
764
  /** PRD §23: variant price converted to the region's currency via the daily
708
765
  * FX snapshot. Present only with `getProducts({ regionId })`. Display-only. */
709
766
  displayPrice?: string;
@@ -1808,6 +1865,8 @@ interface Customer {
1808
1865
  emailVerified: boolean;
1809
1866
  acceptsMarketing: boolean;
1810
1867
  tags: string[];
1868
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. Admin-set only, never customer-editable. */
1869
+ role?: string;
1811
1870
  totalOrders: number;
1812
1871
  lastOrderAt?: string;
1813
1872
  metadata?: Record<string, unknown>;
@@ -1907,6 +1966,8 @@ interface CreateCustomerDto {
1907
1966
  password?: string;
1908
1967
  acceptsMarketing?: boolean;
1909
1968
  tags?: string[];
1969
+ /** Free-form merchant-set segment (e.g. "wholesale", "vip"), max 50 chars. */
1970
+ role?: string;
1910
1971
  metadata?: Record<string, unknown>;
1911
1972
  }
1912
1973
  interface UpdateCustomerDto {
@@ -1916,6 +1977,8 @@ interface UpdateCustomerDto {
1916
1977
  lastName?: string;
1917
1978
  acceptsMarketing?: boolean;
1918
1979
  tags?: string[];
1980
+ /** Free-form merchant-set segment. Pass '' to clear it. */
1981
+ role?: string;
1919
1982
  metadata?: Record<string, unknown>;
1920
1983
  }
1921
1984
  interface CustomerQueryParams {
@@ -1923,6 +1986,8 @@ interface CustomerQueryParams {
1923
1986
  limit?: number;
1924
1987
  search?: string;
1925
1988
  hasAccount?: boolean;
1989
+ /** Filter by merchant-set customer role/segment (exact match, case-insensitive). */
1990
+ role?: string;
1926
1991
  sortBy?: 'createdAt' | 'email' | 'firstName' | 'lastName' | 'lastOrderAt';
1927
1992
  sortOrder?: 'asc' | 'desc';
1928
1993
  }
@@ -3120,6 +3185,8 @@ interface CreateVariantDto {
3120
3185
  attributes?: Record<string, string>;
3121
3186
  price?: number;
3122
3187
  salePrice?: number;
3188
+ /** Variant unit cost (COGS) override — falls back to product costPrice in margin analytics. */
3189
+ costPrice?: number;
3123
3190
  inventory?: number;
3124
3191
  image?: unknown;
3125
3192
  position?: number;
@@ -3131,6 +3198,8 @@ interface UpdateVariantDto {
3131
3198
  attributes?: Record<string, string>;
3132
3199
  price?: number;
3133
3200
  salePrice?: number;
3201
+ /** Variant unit cost (COGS) override. Pass null to clear (falls back to product costPrice). */
3202
+ costPrice?: number | null;
3134
3203
  image?: string | unknown;
3135
3204
  position?: number;
3136
3205
  status?: VariantStatus;
@@ -3149,6 +3218,8 @@ interface BulkVariantInput {
3149
3218
  attributes: Record<string, string>;
3150
3219
  price?: number | null;
3151
3220
  salePrice?: number | null;
3221
+ /** Variant unit cost (COGS) override. null clears (falls back to product costPrice). */
3222
+ costPrice?: number | null;
3152
3223
  stock: number;
3153
3224
  position?: number;
3154
3225
  image?: unknown | null;
@@ -6012,6 +6083,7 @@ declare class BrainerceClient {
6012
6083
  private readonly origin?;
6013
6084
  private readonly proxyMode;
6014
6085
  private readonly onAuthError?;
6086
+ private readonly onCartReset?;
6015
6087
  /** Active locale for content translation. When set, content endpoints return translated data. */
6016
6088
  private locale?;
6017
6089
  constructor(options: BrainerceClientOptions);
@@ -7301,6 +7373,8 @@ declare class BrainerceClient {
7301
7373
  lastName?: string;
7302
7374
  phone?: string;
7303
7375
  emailVerified: boolean;
7376
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. */
7377
+ role?: string;
7304
7378
  }>;
7305
7379
  /**
7306
7380
  * Get all addresses for a customer
@@ -9283,6 +9357,25 @@ declare class BrainerceClient {
9283
9357
  * ```
9284
9358
  */
9285
9359
  cancelMembership(): Promise<PaidMembershipInfo>;
9360
+ /**
9361
+ * Mint a short-lived session for the embeddable loyalty widget (Phase 5) and
9362
+ * return the ready-to-use iframe URL. Requires customerToken. The returned
9363
+ * `embedUrl` is safe to drop straight into an `<iframe src>` — it carries a
9364
+ * scoped ~15-minute session token, never the real customerToken. Re-call this
9365
+ * before the iframe reloads (e.g. on page navigation) to refresh it.
9366
+ *
9367
+ * @example
9368
+ * ```typescript
9369
+ * const { embedUrl } = await client.getLoyaltyWidgetSession();
9370
+ * // <iframe src={embedUrl} width="360" height="420" />
9371
+ * ```
9372
+ */
9373
+ getLoyaltyWidgetSession(): Promise<{
9374
+ sessionId: string;
9375
+ expiresAt: string;
9376
+ storeId: string;
9377
+ embedUrl: string;
9378
+ }>;
9286
9379
  /**
9287
9380
  * Get the current customer's orders (requires customerToken)
9288
9381
  * Works in vibe-coded and storefront modes
@@ -10503,7 +10596,7 @@ declare class BrainerceError extends Error {
10503
10596
  constructor(message: string, statusCode: number, details?: unknown);
10504
10597
  }
10505
10598
 
10506
- declare const SDK_VERSION = "1.45.0";
10599
+ declare const SDK_VERSION = "1.48.0";
10507
10600
 
10508
10601
  /**
10509
10602
  * Verify a webhook signature from Brainerce
@@ -10686,6 +10779,8 @@ declare function buildProductJsonLd(product: Product, opts: JsonLdOptions & {
10686
10779
  currency: string;
10687
10780
  /** Brand display name; falls back to product.brands[0]. */
10688
10781
  brandName?: string;
10782
+ /** Flat-rate/free shipping zones (from `StoreInfo.shipping`). Omitted entirely when not provided — no fabricated shipping cost. */
10783
+ shipping?: ShippingSummaryEntry[];
10689
10784
  }): JsonLd;
10690
10785
  /**
10691
10786
  * schema.org/Organization for the homepage (Knowledge Panel + AI-answer
@@ -10786,4 +10881,4 @@ interface CategorySitemapOptions {
10786
10881
  */
10787
10882
  declare function getCategorySitemapEntries(client: BrainerceClient, opts: CategorySitemapOptions): Promise<SitemapEntry[]>;
10788
10883
 
10789
- export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogSitemapOptions, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartIncludeOption, type CartIncludeOptions, type CartItem, type CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type OrderStatusChange, type PageContent, type PageSeo, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SubmitProductReviewInput, type SupportedLocaleObject, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type UpdateAddressDto, type UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateModifierGroupInput, type UpdateModifierInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseWebhookEvent, safePaymentRedirect, stripHtml, verifyWebhook };
10884
+ export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogSitemapOptions, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartIncludeOption, type CartIncludeOptions, type CartItem, type CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type OrderStatusChange, type PageContent, type PageSeo, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingSummaryEntry, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SubmitProductReviewInput, type SupportedLocaleObject, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type UpdateAddressDto, type UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateModifierGroupInput, type UpdateModifierInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseWebhookEvent, safePaymentRedirect, stripHtml, verifyWebhook };