@brainerce/mcp-server 3.4.0 → 3.5.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/dist/index.mjs CHANGED
@@ -259,9 +259,14 @@ function CheckoutPage() {
259
259
  }
260
260
 
261
261
  // Step 4: Create payment intent \u2014 returns provider type!
262
+ // Pass saveCard: true when the customer ticked "save my card for next time" \u2014
263
+ // only honored for logged-in customers (not guests). The vaulted card then
264
+ // appears in client.listSavedPaymentMethods(storeId, customerId) and can be
265
+ // charged off-session via subscription / one-click checkout flows.
262
266
  const paymentIntent = await client.createPaymentIntent(checkoutId, {
263
267
  successUrl: \`\${window.location.origin}/order-confirmation?checkout_id=\${checkoutId}\`,
264
268
  cancelUrl: \`\${window.location.origin}/checkout?error=payment_cancelled\`,
269
+ // saveCard: customerOptedIn, // optional opt-in
265
270
  });
266
271
 
267
272
  setPaymentData({ clientSecret: paymentIntent.clientSecret, provider: paymentIntent.provider, checkoutId });
@@ -382,8 +387,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
382
387
  }
383
388
  if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
384
389
  // Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
385
- // before navigating \u2014 never trust the URL blindly.
386
- if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
390
+ // before navigating \u2014 never trust the URL blindly. The SDK ships with
391
+ // a maintained list of payment-provider hosts; prefer it over a local
392
+ // copy so 'npm update brainerce' picks up new providers automatically.
393
+ if (isAllowedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
387
394
  }
388
395
  if (data?.type === 'brainerce:payment-complete') {
389
396
  // Payment done \u2014 redirect to confirmation page which verifies server-side
@@ -423,15 +430,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
423
430
  );
424
431
  }
425
432
 
426
- // Allowlist of origins you trust for top-level payment redirects.
427
- function isTrustedPaymentUrl(url: string): boolean {
428
- try {
429
- const u = new URL(url);
430
- if (u.protocol !== 'https:') return false;
431
- // Add your provider hostnames here. Example: Cardcom for Bit express-pay.
432
- return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
433
- } catch { return false; }
434
- }
433
+ // Allowlist check is provided by the SDK \u2014 covers Stripe, PayPal, Cardcom,
434
+ // Meshulam, Grow, CreditGuard, plus Brainerce-hosted embed shells. To extend
435
+ // for a self-hosted PSP, pass { extraHosts: ['my-psp.example.com'] }.
436
+ import { isAllowedPaymentUrl } from 'brainerce';
435
437
  \`\`\`
436
438
 
437
439
  ### PayPal Payment Form
@@ -719,6 +721,80 @@ Provider-specific install notes:
719
721
  - **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
720
722
  - **Cardcom:** No SDK needed \u2014 rendering driven by \`renderType: 'iframe'\` + the inline/modal branch above. Supports credit cards, Bit (when terminal provisions it), installments, 3D Secure.`;
721
723
  }
724
+ function getSavedPaymentMethodsSection() {
725
+ return `## Saved Payment Methods (vaulted cards)
726
+
727
+ When a logged-in customer ticks "save my card for next time", the platform vaults the
728
+ card with the underlying provider and stores a reference. Vaulted cards can later be
729
+ charged off-session \u2014 typically via subscription / one-click checkout features built
730
+ on top of this foundation.
731
+
732
+ ### Opt-in at checkout
733
+
734
+ Pass \`saveCard: true\` to \`createPaymentIntent\` when the customer chose to save.
735
+ **Only honored for logged-in customers** \u2014 anonymous (guest) checkouts silently
736
+ skip vaulting because there's no Customer record to attach the resulting saved
737
+ method to.
738
+
739
+ \`\`\`typescript
740
+ const intent = await client.createPaymentIntent(checkoutId, {
741
+ successUrl,
742
+ cancelUrl,
743
+ saveCard: true, // optional \u2014 only when customer ticked the box AND is logged in
744
+ });
745
+ \`\`\`
746
+
747
+ After a successful charge, the saved card appears in the customer's profile.
748
+
749
+ ### Listing saved cards (storefront / customer account page)
750
+
751
+ Show the customer their saved cards on a "Manage Payment Methods" page in their
752
+ account. The platform returns display-only metadata \u2014 last4, brand, expiry,
753
+ default flag, status. The underlying provider token is encrypted at rest and
754
+ NEVER returned through the SDK.
755
+
756
+ \`\`\`typescript
757
+ const methods = await client.listSavedPaymentMethods(storeId, customerId);
758
+
759
+ methods.forEach((m) => {
760
+ console.log(\`\${m.brand} ending in \${m.last4} (expires \${m.expMonth}/\${m.expYear})\`);
761
+ if (m.isDefault) console.log(' \u21B3 default');
762
+ if (m.status === 'expired') console.log(' \u21B3 expired \u2014 please add a new card');
763
+ });
764
+ \`\`\`
765
+
766
+ ### Removing a saved card
767
+
768
+ \`\`\`typescript
769
+ await client.removeSavedPaymentMethod(storeId, customerId, methodId);
770
+ \`\`\`
771
+
772
+ Hard-deletes the row from the platform DB. The provider may still hold the
773
+ underlying token internally \u2014 we don't issue a delete-at-provider call because
774
+ not every provider supports it. From the platform's perspective the token is
775
+ gone; subsequent charges fail.
776
+
777
+ ### Provider support matrix
778
+
779
+ | Provider | Save card on first charge | Charge saved card off-session |
780
+ |---|---|---|
781
+ | Cardcom | \u2705 (Operation: ChargeAndCreateToken) | \u2705 |
782
+ | PayPal | \u2705 (Vault API: store_in_vault) | \u2705 |
783
+ | Stripe | (separate workstream \u2014 Brainerce doesn't ship a Stripe payment app yet) | \u2014 |
784
+ | Grow | \u274C \u2014 returns 501 \`token_storage_unavailable\` | \u274C |
785
+
786
+ When a provider doesn't support tokenization, the platform surfaces a 409 with
787
+ \`code: 'token_storage_unavailable'\`. Storefronts should hide the "save card"
788
+ checkbox when the active provider doesn't support it.
789
+
790
+ ### Charging off-session
791
+
792
+ Charging a saved card from the storefront is **not** part of this foundation \u2014
793
+ that's the job of the Subscription / one-click checkout features built on top.
794
+ For now, charges run through the standard \`createPaymentIntent\` flow. The
795
+ saved-method foundation makes those features possible without further platform
796
+ changes.`;
797
+ }
722
798
  function getProductsSection(_currency) {
723
799
  return `## Products & Variants
724
800
 
@@ -739,6 +815,18 @@ const filtered = await client.getProducts({
739
815
  categories: ['cat_123'], minPrice: 10, maxPrice: 100,
740
816
  sortBy: 'price', sortOrder: 'asc',
741
817
  });
818
+
819
+ // Filter by custom fields (metafields). Only fields the merchant marked
820
+ // \`filterable: true\` are honored; supported types are SELECT, MULTI_SELECT,
821
+ // BOOLEAN. AND across keys, OR within a key.
822
+ const byCustom = await client.getProducts({
823
+ metafields: { color: ['red', 'blue'], in_stock: ['true'] },
824
+ });
825
+
826
+ // Discover which custom fields are filterable for the current store:
827
+ const { definitions } = await client.getPublicMetafieldDefinitions();
828
+ const facets = definitions.filter(d => d.filterable);
829
+ // Render a checkbox group per SELECT/MULTI_SELECT, a switch per BOOLEAN.
742
830
  \`\`\`
743
831
 
744
832
  ### i18n \u2014 translated fields come back on every request
@@ -1108,22 +1196,24 @@ const { upgrades } = await client.getCartUpgrades(cartId);
1108
1196
  // Show inline banner per cart item if upgrade exists
1109
1197
  \`\`\`
1110
1198
 
1111
- **Bundle offers** (discounted complementary products configured by the store owner):
1199
+ **Bundle offers** (N-product bundles configured by the store owner \u2014 productIds[0] triggers the offer, productIds[1..] are offered together at a discount):
1112
1200
  \`\`\`typescript
1113
1201
  import type { CartBundlesResponse } from 'brainerce';
1114
1202
  const { bundles } = await client.getCartBundles(cartId);
1115
- // bundles[].bundleProduct \u2014 the product to offer
1116
- // bundles[].originalPrice / bundles[].discountedPrice \u2014 prices
1203
+ // bundles[].triggerProductId \u2014 already in cart, activates the offer
1204
+ // bundles[].productIds \u2014 full bundle composition (length >= 2)
1205
+ // bundles[].offeredProducts[] \u2014 products customer hasn't added yet
1206
+ // each with originalPrice + discountedPrice
1207
+ // bundles[].totalOriginalPrice / totalDiscountedPrice \u2014 sums across offeredProducts
1117
1208
  // bundles[].discountType ('PERCENTAGE' | 'FIXED_AMOUNT') + discountValue
1118
- // bundles[].requiresVariantSelection \u2014 true if customer must pick a variant
1119
- // bundles[].lockedVariant \u2014 set if admin pre-selected a specific variant
1120
- // bundles[].bundleProduct.variants \u2014 available variants (only when requiresVariantSelection)
1121
1209
 
1122
- // Add a bundle to cart (applies the discount automatically):
1210
+ // Accept a bundle (adds every offered product not yet in cart at the discount):
1123
1211
  await client.addBundleToCart(cartId, bundleOfferId);
1124
- // For products with variants \u2014 pass the selected variantId:
1125
- await client.addBundleToCart(cartId, bundleOfferId, selectedVariantId);
1126
- // Remove a bundle from cart:
1212
+ // If some offered products have variants, pass per-product variant selections:
1213
+ await client.addBundleToCart(cartId, bundleOfferId, {
1214
+ [variantProductId]: selectedVariantId,
1215
+ });
1216
+ // Remove an accepted bundle (removes every cart item linked to that bundle):
1127
1217
  await client.removeBundleFromCart(cartId, bundleOfferId);
1128
1218
  // Detect already-added bundles: check cart.items for metadata?.isBundleItem === true
1129
1219
  \`\`\`
@@ -1179,11 +1269,12 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
1179
1269
  | CartRecommendationSection | products/ | Cross-sell grid at bottom of cart page |
1180
1270
  | FreeShippingBar | cart/ | Progress bar toward free shipping threshold |
1181
1271
  | CartUpgradeBanner | cart/ | Inline "Upgrade to X for +$Y" per cart item |
1182
- | CartBundleOfferCard | cart/ | Discounted bundle offer card in cart (with inline variant selector for variable products) |
1272
+ | CartBundleOfferCard | cart/ | N-product bundle offer card in cart \u2014 lists every offered product with its discounted price and an "Add bundle" button |
1183
1273
  | OrderBumpCard | checkout/ | Checkbox add-on card in checkout sidebar (with inline variant selector for variable products) |
1184
1274
 
1185
1275
  ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
1186
- OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
1276
+ OrderBump: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).
1277
+ CartBundleOffer: \`productIds\` (length \\>= 2; index 0 = trigger), \`offeredProducts\` (per-product discounted prices), \`totalOriginalPrice\` / \`totalDiscountedPrice\`. Variant selection for offered products is passed per-call via \`variantSelections\` on \`addBundleToCart\`.`;
1187
1278
  }
1188
1279
  function getProductCustomizationFieldsSection() {
1189
1280
  return `## Product Customization Fields (buyer input on product page)
@@ -1289,6 +1380,157 @@ When the order is created, each line's customization values are snapshotted onto
1289
1380
  - Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
1290
1381
  - Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
1291
1382
  }
1383
+ function getModifierGroupsSection() {
1384
+ return `## Modifier Groups (toppings, sauce, build-your-own)
1385
+
1386
+ Modifier groups are merchant-defined option blocks attached to a product \u2014 the canonical example is "Toppings" on a pizza, where the customer picks 0\u20138 options with the first 3 free. They differ from \`customizationFields\` (which are arbitrary buyer input \u2014 text, photos, color picks): modifier groups are a **structured selection with priced options**, validated and priced server-side.
1387
+
1388
+ If \`product.modifierGroups\` is empty or missing, render the product page normally and skip everything below.
1389
+
1390
+ ### Wire shape on \`GET /products/:id\`
1391
+
1392
+ \`\`\`typescript
1393
+ import type { Product, ModifierGroup, Modifier, ModifierSelection } from 'brainerce';
1394
+
1395
+ const product = await client.getProductBySlug(slug);
1396
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
1397
+
1398
+ // Each group looks like:
1399
+ // {
1400
+ // id: 'mg_toppings',
1401
+ // attachmentId: 'pmg_01', // ProductModifierGroup row \u2014 used for attach updates
1402
+ // name: 'Toppings', // customer-facing
1403
+ // internalName?: string, // ADMIN ONLY \u2014 never present in storefront responses
1404
+ // selectionType: 'SINGLE' | 'MULTIPLE',
1405
+ // min: number, // effective (overrides already applied)
1406
+ // max: number | null, // null = unlimited; **0 = group hidden for this variant**
1407
+ // freeQuantity: number, // first N picks at no extra cost
1408
+ // required: boolean,
1409
+ // freeAllocationPolicy: 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER',
1410
+ // defaultModifierIds: string[], // pre-checked on first render
1411
+ // modifiers: Array<{
1412
+ // id: 'm_olive',
1413
+ // name: 'Olives',
1414
+ // priceDelta: '5.00', // DECIMAL STRING \u2014 never JSON Number
1415
+ // position: 0,
1416
+ // isDefault: false, // pre-check this option even if not in defaultModifierIds
1417
+ // available: true, // false \u2192 "sold out", disabled in UI
1418
+ // referencedProductId?: string, // nested-combo target (depth \u2264 3)
1419
+ // }>,
1420
+ // }
1421
+ \`\`\`
1422
+
1423
+ **Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
1424
+
1425
+ ### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
1426
+
1427
+ Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
1428
+
1429
+ \`\`\`typescript
1430
+ for (const group of groups) {
1431
+ if (group.max === 0) continue; // disabled-for-variant convention \u2014 skip entirely
1432
+ const inputType = group.selectionType === 'SINGLE' ? 'radio' : 'checkbox';
1433
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
1434
+ // Render fieldset \u2192 legend with name + " *" if required \u2192 list of sorted options.
1435
+ // Each option: input(type=inputType, name=group.id, value=modifier.id),
1436
+ // disabled when modifier.available === false, with a "Sold out" badge.
1437
+ }
1438
+ \`\`\`
1439
+
1440
+ When \`group.freeQuantity > 0\`, show a running counter so the customer understands the rule:
1441
+ \`\`\`
1442
+ {Math.min(picks.length, group.freeQuantity)} of {group.freeQuantity} free
1443
+ \`\`\`
1444
+
1445
+ Note: individual modifiers may have \`excludeFromFree: true\` \u2014 these are "premium" options that always charge their \`priceDelta\` and are never consumed by a free slot. Render them with a label like "premium" so customers know they are not eligible for the free allocation.
1446
+
1447
+ ### Initial state
1448
+
1449
+ Honor \`defaultModifierIds\` first (per-attach defaults set by the merchant for this product/variant), falling back to \`modifier.isDefault\` flags when the group has no per-attach defaults. Filter sold-out modifiers out of the initial picks. For SINGLE groups, cap to one.
1450
+
1451
+ ### Pass selections on add-to-cart
1452
+
1453
+ \`\`\`typescript
1454
+ const selections: ModifierSelection[] = [
1455
+ { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
1456
+ { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom', 'm_bacon', 'm_egg'] },
1457
+ ];
1458
+
1459
+ await client.smartAddToCart({
1460
+ productId: product.id,
1461
+ variantId: selectedVariant?.id,
1462
+ quantity: 1,
1463
+ selections,
1464
+ });
1465
+ \`\`\`
1466
+
1467
+ \`modifierIds\` is in **click-order** \u2014 the server uses this for the \`SELECTION_ORDER\` free-allocation policy. The cart response surfaces a per-line snapshot:
1468
+
1469
+ \`\`\`typescript
1470
+ // cart.items[i].modifiers \u2014 same shape as ModifierSelection but with snapshot data
1471
+ [
1472
+ { modifierId: 'm_olive', name: 'Olives', priceDelta: '5.00', freeApplied: true },
1473
+ { modifierId: 'm_mushroom', name: 'Mushrooms', priceDelta: '5.00', freeApplied: true },
1474
+ { modifierId: 'm_bacon', name: 'Bacon', priceDelta: '7.00', freeApplied: true },
1475
+ { modifierId: 'm_egg', name: 'Egg', priceDelta: '6.00', freeApplied: false },
1476
+ ]
1477
+ // + cart.items[i].modifiersTotal \u2014 sum of paid (non-free) deltas as a decimal string
1478
+ \`\`\`
1479
+
1480
+ \`freeApplied: true\` means the modifier consumed a free slot \u2014 render with a "free" badge in the cart UI.
1481
+
1482
+ ### Editing selections after add-to-cart (idempotent)
1483
+
1484
+ \`PATCH /cart/items/:id\` with a fresh \`selections\` array **replaces** the line's modifiers atomically \u2014 the server deletes old \`CartItemModifier\` rows and recreates them inside the same transaction. Omit \`selections\` from the body to leave them unchanged (e.g., quantity-only update).
1485
+
1486
+ \`\`\`typescript
1487
+ await client.updateCartItem(cart.id, itemId, {
1488
+ quantity: 1,
1489
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom'] }],
1490
+ });
1491
+ \`\`\`
1492
+
1493
+ ### Validation envelope
1494
+
1495
+ When the payload is invalid the server returns HTTP 400 with a structured envelope. The SDK exposes it on \`BrainerceError.details\`:
1496
+
1497
+ \`\`\`typescript
1498
+ try {
1499
+ await client.smartAddToCart({ productId, quantity: 1, selections });
1500
+ } catch (err) {
1501
+ const e = err as { statusCode?: number; details?: { code?: string; errors?: Array<{ code: string; message: string; modifierGroupId?: string; modifierId?: string }> } };
1502
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
1503
+ for (const issue of e.details.errors ?? []) {
1504
+ // issue.code is one of: REQUIRED_GROUP_MISSING | MIN_SELECTIONS_NOT_MET |
1505
+ // MAX_SELECTIONS_EXCEEDED | SINGLE_GROUP_MULTIPLE_PICKS | UNKNOWN_MODIFIER |
1506
+ // UNKNOWN_GROUP | MODIFIER_DISABLED_FOR_VARIANT | MODIFIER_NOT_AVAILABLE |
1507
+ // NESTED_DEPTH_EXCEEDED | NESTED_REQUIRES_PRODUCT_REF | INVALID_PRICE_DELTA |
1508
+ // MODIFIER_PRICE_FLOOR_VIOLATED
1509
+ console.error(issue.message);
1510
+ }
1511
+ }
1512
+ }
1513
+ \`\`\`
1514
+
1515
+ Special case: \`MODIFIER_PRICE_FLOOR_VIOLATED\` fires when downsell modifiers (negative \`priceDelta\`) would push \`unitPrice\` below \`0\`. The server reports a generic message \u2014 internals never leak \u2014 so show a friendly "Cannot apply more discounts on this item" and let the customer remove a downsell.
1516
+
1517
+ ### Disable-for-variant convention (PRD \xA77.2.2)
1518
+
1519
+ The merchant can hide a group entirely for one variant by setting \`maxOverride: 0\` on a per-variant attachment. The product response then returns the group with \`max: 0\` for that variant. **Skip it entirely** \u2014 do not render, do not include in selections. The validator silently skips groups with \`effectiveMax === 0\` on the cart side.
1520
+
1521
+ ### Common mistakes
1522
+
1523
+ - Treating \`priceDelta\` as a number \u2192 arithmetic precision bugs. Always strings; use \`parseFloat\` only at display time.
1524
+ - Computing the line total client-side \u2192 diverges from the server's free-allocation. Render the server's \`unitPrice\` / \`modifiers[]\` / \`modifiersTotal\` instead.
1525
+ - Rendering a group with \`max: 0\` \u2192 it's the variant-disable signal; treat as absent.
1526
+ - Showing \`internalName\` on a public storefront \u2192 it is **never** present in storefront responses; if your code is reading it, you're using an admin endpoint by accident.
1527
+ - Building \`selections\` keyed by \`modifier.name\` \u2192 must be \`modifierGroupId\` + \`modifierIds[]\` (the IDs, not names).
1528
+ - Sending \`modifiers\` instead of \`selections\` on add-to-cart \u2192 \`modifiers\` is the response field; the request key is \`selections\`.
1529
+
1530
+ ### Restaurant features (advanced)
1531
+
1532
+ Allergens (informational chips), scheduled availability windows, nested combos (depth \u2264 3 via \`nestedByModifierId\`), and downsell modifiers (negative \`priceDelta\`) are all built on the same data model. See INTEGRATION-OPTIONAL.md "Restaurant / build-your-own products" for those flows.`;
1533
+ }
1292
1534
  function getInventorySection() {
1293
1535
  return `## Inventory, Stock Display & Reservation Countdown
1294
1536
 
@@ -1854,7 +2096,40 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
1854
2096
  // Email: getEmailTemplates(), createEmailTemplate()
1855
2097
  // Conflicts: getSyncConflicts(), resolveSyncConflict()
1856
2098
  // OAuth: getOAuthProviders(), configureOAuthProvider()
1857
- \`\`\``;
2099
+ \`\`\`
2100
+
2101
+ ### Per-Channel Publishing
2102
+
2103
+ Categories, tags, brands, and metafield definitions are gated to specific
2104
+ vibe-coded sites \u2014 same control already exposed for products and coupons.
2105
+ **Explicit opt-in:** an entity is visible to a vibe-coded site only if it
2106
+ has been explicitly published to that connection. Entities with no publish
2107
+ rows are invisible to every site (the merchant must publish them via the
2108
+ dashboard or the admin SDK).
2109
+
2110
+ \`\`\`typescript
2111
+ // Publish to a specific vibe-coded site (admin mode):
2112
+ await admin.publishCategoryToVibeCodedSite('cat_id', 'conn_id');
2113
+ await admin.publishTagToVibeCodedSite('tag_id', 'conn_id');
2114
+ await admin.publishBrandToVibeCodedSite('brand_id', 'conn_id');
2115
+ await admin.publishMetafieldDefinitionToVibeCodedSite('def_id', 'conn_id');
2116
+
2117
+ // Unpublish (entity stays visible to other sites unless they also have publishes):
2118
+ await admin.unpublishCategoryFromVibeCodedSite('cat_id', 'conn_id');
2119
+ // ...same for tag/brand/metafield definition.
2120
+
2121
+ // Read which sites an entity is published to via list/get responses:
2122
+ const cat = await admin.getCategory('cat_id');
2123
+ cat.vibeCodedPublishes; // [{ connection: { id, name, connectionId } }, ...]
2124
+ \`\`\`
2125
+
2126
+ Cross-account isolation is enforced server-side: a publish call only
2127
+ succeeds when entity and connection belong to the same account. Cross-account
2128
+ calls fail with \`404 Not Found\`.
2129
+
2130
+ The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
2131
+ mode) automatically filter by these junction tables, so storefronts never see
2132
+ entities that weren't published to their site.`;
1858
2133
  }
1859
2134
  function getContactInquiriesSection() {
1860
2135
  return `## Contact Inquiries & Forms (optional)
@@ -1929,7 +2204,7 @@ const form = await brainerce.contactForms.get('main', 'en');
1929
2204
  // \u2192 {
1930
2205
  // id, key, name, description?, submitButton, successMessage,
1931
2206
  // fields: [{ key, type, label, placeholder?, helpText?, isRequired,
1932
- // enumValues?, validation?, defaultValue? }, ...]
2207
+ // enumValues?, validation?, defaultValue?, width? }, ...]
1933
2208
  // }
1934
2209
 
1935
2210
  // Submit a keyed payload. Unknown keys are stripped, required fields are
@@ -1955,6 +2230,20 @@ stripped server-side.
1955
2230
  Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
1956
2231
  component so the form is fully driven by \`schema.fields\`.
1957
2232
 
2233
+ **Layout.** Each field carries an optional \`width\` hint:
2234
+
2235
+ | \`field.width\` | Meaning | Grid style (6-column grid) |
2236
+ | ------------- | ------- | -------------------------- |
2237
+ | \`'FULL'\` (default) | Full row | \`grid-column: span 6\` |
2238
+ | \`'HALF'\` | Half row | \`grid-column: span 3\` |
2239
+ | \`'THIRD'\` | One-third row | \`grid-column: span 2\` |
2240
+
2241
+ Stack fields to full width on small screens (< ~640 px).
2242
+
2243
+ **Required fields.** Show a red asterisk on required labels, validate
2244
+ **client-side** before calling \`createInquiry()\`, and show inline error
2245
+ messages. Do NOT rely only on the server returning 400.
2246
+
1958
2247
  \`\`\`tsx
1959
2248
  import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
1960
2249
 
@@ -1972,13 +2261,24 @@ function isEmpty(v: FieldValue): boolean {
1972
2261
  return v === false;
1973
2262
  }
1974
2263
 
2264
+ // Map width \u2192 CSS grid column span (6-column grid)
2265
+ function widthClass(w?: string): string {
2266
+ switch (w) {
2267
+ case 'HALF': return 'grid-col-half'; // grid-column: span 3; on sm+, full on mobile
2268
+ case 'THIRD': return 'grid-col-third'; // grid-column: span 2; on sm+, full on mobile
2269
+ default: return 'grid-col-full'; // grid-column: span 6
2270
+ }
2271
+ }
2272
+
1975
2273
  function DynamicField({
1976
2274
  field,
1977
2275
  value,
2276
+ error,
1978
2277
  onChange,
1979
2278
  }: {
1980
2279
  field: ContactFormPublicField;
1981
2280
  value: FieldValue;
2281
+ error?: string;
1982
2282
  onChange: (v: FieldValue) => void;
1983
2283
  }) {
1984
2284
  const id = \`contact-\${field.key}\`;
@@ -1993,37 +2293,40 @@ function DynamicField({
1993
2293
  </label>
1994
2294
  );
1995
2295
  const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
2296
+ const errorEl = error ? <p className="mt-1 text-xs text-red-500">{error}</p> : null;
1996
2297
 
2298
+ // Outer div uses widthClass to control grid-column span
1997
2299
  switch (field.type) {
1998
2300
  case 'TEXTAREA':
1999
- return (<div>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2301
+ return (<div className={widthClass(field.width)}>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2000
2302
  case 'EMAIL':
2001
- return (<div>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2303
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2002
2304
  case 'PHONE':
2003
- return (<div>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2305
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2004
2306
  case 'URL':
2005
- return (<div>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2307
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2006
2308
  case 'NUMBER':
2007
- return (<div>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2309
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2008
2310
  case 'DATE':
2009
- return (<div>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2311
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2010
2312
  case 'SELECT':
2011
- return (<div>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}</div>);
2313
+ return (<div className={widthClass(field.width)}>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}{errorEl}</div>);
2012
2314
  case 'MULTI_SELECT': {
2013
2315
  const arr = Array.isArray(value) ? value : [];
2014
- return (<div>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}</div>);
2316
+ return (<div className={widthClass(field.width)}>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}{errorEl}</div>);
2015
2317
  }
2016
2318
  case 'CHECKBOX':
2017
- return (<div><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}</div>);
2319
+ return (<div className={widthClass(field.width)}><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}{errorEl}</div>);
2018
2320
  case 'TEXT':
2019
2321
  default:
2020
- return (<div>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
2322
+ return (<div className={widthClass(field.width)}>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
2021
2323
  }
2022
2324
  }
2023
2325
 
2024
2326
  export function ContactPage() {
2025
2327
  const [schema, setSchema] = useState<ContactFormPublic | null>(null);
2026
2328
  const [values, setValues] = useState<Record<string, FieldValue>>({});
2329
+ const [errors, setErrors] = useState<Record<string, string>>({});
2027
2330
  const [honeypot, setHoneypot] = useState('');
2028
2331
  const [sent, setSent] = useState(false);
2029
2332
  const [loading, setLoading] = useState(false);
@@ -2047,6 +2350,19 @@ export function ContactPage() {
2047
2350
  if (loading) return;
2048
2351
  if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
2049
2352
 
2353
+ // \u2500\u2500 Client-side required-field validation \u2500\u2500
2354
+ const newErrors: Record<string, string> = {};
2355
+ for (const f of schema.fields) {
2356
+ if (f.isRequired && isEmpty(values[f.key] ?? defaultValueFor(f))) {
2357
+ newErrors[f.key] = \`\${f.label} is required\`; // or pull from your i18n system
2358
+ }
2359
+ }
2360
+ if (Object.keys(newErrors).length > 0) {
2361
+ setErrors(newErrors);
2362
+ return; // block submission
2363
+ }
2364
+ setErrors({});
2365
+
2050
2366
  setLoading(true);
2051
2367
  try {
2052
2368
  const payload: Record<string, unknown> = {};
@@ -2079,11 +2395,15 @@ export function ContactPage() {
2079
2395
  value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
2080
2396
  </div>
2081
2397
 
2082
- {schema.fields.map((field) => (
2083
- <DynamicField key={field.key} field={field}
2084
- value={values[field.key] ?? defaultValueFor(field)}
2085
- onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2086
- ))}
2398
+ {/* CSS grid \u2014 6 columns on sm+, 1 column on mobile */}
2399
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '1rem' }}>
2400
+ {schema.fields.map((field) => (
2401
+ <DynamicField key={field.key} field={field}
2402
+ value={values[field.key] ?? defaultValueFor(field)}
2403
+ error={errors[field.key]}
2404
+ onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
2405
+ ))}
2406
+ </div>
2087
2407
 
2088
2408
  <button type="submit" disabled={loading}>
2089
2409
  {loading ? '\u2026' : schema.submitButton}
@@ -2093,13 +2413,27 @@ export function ContactPage() {
2093
2413
  }
2094
2414
  \`\`\`
2095
2415
 
2416
+ CSS for the grid column helpers (or use the equivalent Tailwind / inline styles):
2417
+
2418
+ \`\`\`css
2419
+ .grid-col-full { grid-column: span 6; }
2420
+ .grid-col-half { grid-column: span 6; }
2421
+ .grid-col-third { grid-column: span 6; }
2422
+
2423
+ @media (min-width: 640px) {
2424
+ .grid-col-half { grid-column: span 3; }
2425
+ .grid-col-third { grid-column: span 2; }
2426
+ }
2427
+ \`\`\`
2428
+
2096
2429
  ### Rules
2097
2430
 
2098
2431
  - **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
2099
2432
  - **Honeypot:** always render a hidden field named \`honeypot\` and **never send** it. Bots fill every input; the server rejects submissions carrying a non-empty \`honeypot\`.
2100
2433
  - **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
2101
2434
  - **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
2102
- - **Required fields:** respect \`field.isRequired\`. The server validates too, but show \`required\` on the input for browser-level UX.
2435
+ - **Required fields:** respect \`field.isRequired\`. Show a red asterisk (\`*\`) next to the label. **Validate client-side before submission** \u2014 iterate over \`schema.fields\`, check \`isEmpty(values[f.key])\` for each required field, and block the submit with inline error messages. The server validates too, but the user should never see a raw 400 error.
2436
+ - **Width (layout):** respect \`field.width\`. Use a CSS grid with 6 columns: \`FULL\` = span 6 (default), \`HALF\` = span 3, \`THIRD\` = span 2. Stack to full width on small screens. If \`width\` is missing, treat as \`FULL\`.
2103
2437
  - **Validation:** when \`field.validation.pattern\` is present, pass it as the input's \`pattern\` attribute; the server also enforces it. Likewise \`minLength\`/\`maxLength\`/\`min\`/\`max\`.
2104
2438
  - **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
2105
2439
  - **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
@@ -2131,6 +2465,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2131
2465
  return getCheckoutCustomFieldsSection();
2132
2466
  case "payment":
2133
2467
  return getPaymentProvidersSection();
2468
+ case "saved-payment-methods":
2469
+ return getSavedPaymentMethodsSection();
2134
2470
  case "auth":
2135
2471
  return getCustomerAuthSection();
2136
2472
  case "order-confirmation":
@@ -2143,6 +2479,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2143
2479
  return getRecommendationsSection();
2144
2480
  case "product-customization-fields":
2145
2481
  return getProductCustomizationFieldsSection();
2482
+ case "modifier-groups":
2483
+ return getModifierGroupsSection();
2146
2484
  case "tax":
2147
2485
  return getTaxDisplaySection(cur);
2148
2486
  case "i18n":
@@ -2223,6 +2561,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2223
2561
  "",
2224
2562
  "---",
2225
2563
  "",
2564
+ getModifierGroupsSection(),
2565
+ "",
2566
+ "---",
2567
+ "",
2226
2568
  getTaxDisplaySection(cur),
2227
2569
  "",
2228
2570
  "---",
@@ -2267,11 +2609,19 @@ var GET_SDK_DOCS_SCHEMA = {
2267
2609
  "inquiries",
2268
2610
  "all"
2269
2611
  ]).describe("The SDK documentation topic to retrieve"),
2270
- connectionId: z.string().optional().describe("Vibe-coded connection ID (starts with vc_). Used to personalize setup code."),
2612
+ salesChannelId: z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
2613
+ /** @deprecated alias of salesChannelId */
2614
+ connectionId: z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat"),
2271
2615
  currency: z.string().optional().describe("Store currency code (e.g., USD, ILS, EUR). Used in price formatting examples.")
2272
2616
  };
2273
2617
  async function handleGetSdkDocs(args) {
2274
- const content = getSectionByTopic(args.topic, args.connectionId, args.currency);
2618
+ const id = args.salesChannelId ?? args.connectionId;
2619
+ if (!args.salesChannelId && args.connectionId) {
2620
+ console.warn(
2621
+ "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2622
+ );
2623
+ }
2624
+ const content = getSectionByTopic(args.topic, id, args.currency);
2275
2625
  return {
2276
2626
  content: [{ type: "text", text: content }]
2277
2627
  };
@@ -2310,7 +2660,7 @@ interface Product {
2310
2660
  attributeId: string;
2311
2661
  attributeOptionId: string;
2312
2662
  platform: string;
2313
- attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' } | null;
2663
+ attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' | 'MIXED_SWATCH' } | null;
2314
2664
  attributeOption: { id: string; name: string; value?: string | null; swatchColor?: string | null; swatchColor2?: string | null; swatchImageUrl?: string | null } | null;
2315
2665
  }>;
2316
2666
  createdAt: string;
@@ -2319,6 +2669,8 @@ interface Product {
2319
2669
 
2320
2670
  // Use getProductSwatches(product) to get grouped swatch data for storefront rendering.
2321
2671
  // Returns Array<{ attributeName, displayType, options: Array<{ name, swatchColor?, swatchColor2?, swatchImageUrl? }> }>
2672
+ // displayType rendering: COLOR_SWATCH \u2192 color circle (swatchColor/swatchColor2); IMAGE_SWATCH \u2192 image thumbnail (swatchImageUrl);
2673
+ // MIXED_SWATCH \u2192 per-option: render swatchImageUrl if set, else swatchColor if set, else text only.
2322
2674
 
2323
2675
  interface ProductImage {
2324
2676
  url: string;
@@ -2399,6 +2751,10 @@ interface ProductQueryParams {
2399
2751
  tags?: string | string[];
2400
2752
  minPrice?: number;
2401
2753
  maxPrice?: number;
2754
+ // Filter by custom-field (metafield) values. Keys = definition.key,
2755
+ // values = accepted values. Only definitions with filterable=true and
2756
+ // type SELECT/MULTI_SELECT/BOOLEAN are honored. AND across keys, OR within.
2757
+ metafields?: Record<string, string | string[]>;
2402
2758
  sortBy?: 'name' | 'price' | 'createdAt';
2403
2759
  sortOrder?: 'asc' | 'desc';
2404
2760
  }
@@ -2816,6 +3172,36 @@ interface PaymentStatus {
2816
3172
  error?: string;
2817
3173
  }
2818
3174
 
3175
+ // ---- Saved Payment Methods (vaulted cards) ----
3176
+ // Display-only summary of a customer's vaulted payment method. The
3177
+ // underlying provider token is encrypted at rest in the platform DB
3178
+ // and NEVER returned through the SDK.
3179
+ //
3180
+ // To opt into vaulting at checkout, pass saveCard: true to
3181
+ // createPaymentIntent (only honored for logged-in customers).
3182
+ //
3183
+ // To list / remove saved methods, see:
3184
+ // client.listSavedPaymentMethods(storeId, customerId)
3185
+ // client.removeSavedPaymentMethod(storeId, customerId, methodId)
3186
+
3187
+ interface SavedPaymentMethodSummary {
3188
+ id: string;
3189
+ customerId: string;
3190
+ appInstallationId: string;
3191
+ paymentMethod: string; // 'credit_card' | 'paypal' | 'bank_account'
3192
+ brand: string | null;
3193
+ last4: string | null;
3194
+ expMonth: number | null;
3195
+ expYear: number | null;
3196
+ isDefault: boolean;
3197
+ status: string; // 'active' | 'expired' | 'invalid'
3198
+ failureReason: string | null;
3199
+ lastUsedAt: string | null;
3200
+ expiresAt: string | null;
3201
+ createdAt: string;
3202
+ updatedAt: string;
3203
+ }
3204
+
2819
3205
  interface WaitForOrderResult {
2820
3206
  success: boolean;
2821
3207
  status: PaymentStatus; // Access: result.status.orderNumber
@@ -2915,15 +3301,32 @@ interface CartUpgradeSuggestion {
2915
3301
  priceDelta: string;
2916
3302
  deltaPercent: number;
2917
3303
  }
2918
- interface CartBundleOffer {
3304
+ interface CartBundleOfferOfferedProduct {
2919
3305
  id: string;
2920
- bundleProduct: ProductRecommendation;
3306
+ name: string;
3307
+ slug: string | null;
3308
+ basePrice: string;
3309
+ salePrice: string | null;
3310
+ images: Array<{ url: string }>;
3311
+ type: string;
2921
3312
  originalPrice: string;
2922
3313
  discountedPrice: string;
3314
+ }
3315
+ interface CartBundleOffer {
3316
+ id: string;
3317
+ name: string;
3318
+ description: string | null;
3319
+ // productIds[0] = trigger product (must be in cart for the bundle to surface);
3320
+ // productIds[1..] = offered together at the bundle discount.
3321
+ triggerProductId: string;
3322
+ productIds: string[];
3323
+ // offeredProducts = productIds[1..] minus those already in cart, each with
3324
+ // its own original/discounted price applied.
3325
+ offeredProducts: CartBundleOfferOfferedProduct[];
2923
3326
  discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
2924
- discountValue: number;
2925
- requiresVariantSelection: boolean;
2926
- lockedVariant?: { id: string; name?: string };
3327
+ discountValue: string;
3328
+ totalOriginalPrice: string;
3329
+ totalDiscountedPrice: string;
2927
3330
  }`;
2928
3331
  var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
2929
3332
 
@@ -2978,6 +3381,7 @@ interface ContactFormPublicField {
2978
3381
  enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
2979
3382
  validation?: ContactFormFieldValidation;
2980
3383
  defaultValue?: string;
3384
+ width?: 'FULL' | 'HALF' | 'THIRD'; // layout hint \u2014 FULL = full row, HALF = half row, THIRD = one-third row
2981
3385
  }
2982
3386
 
2983
3387
  interface ContactFormPublic {
@@ -3009,6 +3413,19 @@ interface ContactFormSummary {
3009
3413
  // MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
3010
3414
  // CHECKBOX \u2192 single <input type="checkbox">, value is boolean
3011
3415
  // ------------------------------------------------------------------
3416
+ //
3417
+ // Layout: render fields inside a CSS grid container.
3418
+ // width='FULL' (default) \u2192 span entire row
3419
+ // width='HALF' \u2192 span half the row (two HALF fields sit side-by-side)
3420
+ // width='THIRD' \u2192 span one-third of the row (three THIRD fields sit side-by-side)
3421
+ // Use a 6-column grid for clean divisibility:
3422
+ // FULL \u2192 col-span-6 | HALF \u2192 col-span-3 | THIRD \u2192 col-span-2
3423
+ // Stack to full width on small screens (< sm breakpoint).
3424
+ //
3425
+ // Required fields: show a red asterisk (*) next to the label, validate
3426
+ // client-side before submission, and display inline error messages for
3427
+ // any empty required field. Do NOT rely only on the server returning 400.
3428
+ // ------------------------------------------------------------------
3012
3429
 
3013
3430
  // SDK methods
3014
3431
  // await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
@@ -3021,6 +3438,130 @@ interface ContactFormSummary {
3021
3438
  // - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
3022
3439
  // - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
3023
3440
  // - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
3441
+ var MODIFIER_GROUPS_TYPES = `// ---- Modifier Groups (Restaurant / Build-Your-Own) ----
3442
+ // Modifier groups are merchant-defined option blocks attached to a product
3443
+ // (toppings, sauce, bread type, \u2026). They differ from product.customizationFields:
3444
+ // modifier groups are STRUCTURED priced choices validated server-side, while
3445
+ // customizationFields are arbitrary buyer input (text/photo/color).
3446
+ //
3447
+ // Money fields are decimal STRINGS on the wire \u2014 "5.00", "-2.00" (downsell).
3448
+ // Never JSON Number. Use parseFloat() only at display time. Do not compute
3449
+ // the line total client-side; the server runs free-allocation and returns
3450
+ // cart.items[i].unitPrice + .modifiers[] + .modifiersTotal.
3451
+
3452
+ export type ModifierSelectionType = 'SINGLE' | 'MULTIPLE';
3453
+
3454
+ export type FreeAllocationPolicy = 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER';
3455
+
3456
+ export interface Modifier {
3457
+ id: string;
3458
+ name: string;
3459
+ description?: string;
3460
+ /** Decimal string. Negative values = downsell modifiers ("-2.00"). */
3461
+ priceDelta: string;
3462
+ sku?: string;
3463
+ image?: { url: string; thumbnailUrl?: string; alt?: string };
3464
+ position: number;
3465
+ /** Pre-checked on first render. */
3466
+ isDefault: boolean;
3467
+ /** false = sold out \u2014 disable in UI with a "Sold out" badge. */
3468
+ available: boolean;
3469
+ /** When true, never applied as a free selection \u2014 always charges priceDelta even when freeQuantity > 0 on the group. */
3470
+ excludeFromFree?: boolean;
3471
+ /** Nested combo: opens a sub-flow; depth \u2264 3 enforced server-side. */
3472
+ referencedProductId?: string;
3473
+ translations?: Record<string, { name?: string; description?: string }>;
3474
+ }
3475
+
3476
+ export interface ModifierGroup {
3477
+ id: string;
3478
+ /**
3479
+ * Set when fetched in a product context (the ProductModifierGroup row id).
3480
+ * Use this to update or detach the attachment without reattaching the group.
3481
+ */
3482
+ attachmentId?: string;
3483
+ /** Customer-facing canonical name. */
3484
+ name: string;
3485
+ /**
3486
+ * Admin-only disambiguator \u2014 NEVER present in storefront responses.
3487
+ * If your client code reads this, you're hitting an admin endpoint by mistake.
3488
+ */
3489
+ internalName?: string;
3490
+ description?: string;
3491
+ selectionType: ModifierSelectionType;
3492
+ /** Effective minimum after any per-attach / per-variant overrides. */
3493
+ min: number;
3494
+ /** Effective maximum; null = unlimited. **0 = group hidden for this variant** (PRD \xA77.2.2). */
3495
+ max?: number | null;
3496
+ freeQuantity: number;
3497
+ required: boolean;
3498
+ freeAllocationPolicy: FreeAllocationPolicy;
3499
+ modifiers: Modifier[];
3500
+ /** Effective default selections (after attachment-level overrides). */
3501
+ defaultModifierIds: string[];
3502
+ translations?: Record<string, { name?: string; description?: string }>;
3503
+ }
3504
+
3505
+ /** Customer-side selection payload \u2014 modifierIds in click-order. */
3506
+ export interface ModifierSelection {
3507
+ modifierGroupId: string;
3508
+ modifierIds: string[];
3509
+ }
3510
+
3511
+ /** Per-line modifier breakdown surfaced on cart.items[i] / order.items[i]. */
3512
+ export interface CartItemModifierLine {
3513
+ modifierId: string;
3514
+ /** Snapshot of the modifier's name at the time the line was added. */
3515
+ name: string;
3516
+ /** Decimal string snapshot of the priceDelta at the time the line was added. */
3517
+ priceDelta: string;
3518
+ /** True if this modifier consumed one of the group's free slots. */
3519
+ freeApplied: boolean;
3520
+ }
3521
+
3522
+ /**
3523
+ * Stable error codes returned in the structured 400 envelope when a cart
3524
+ * payload fails server-side validation. The SDK exposes the envelope on
3525
+ * BrainerceError.details \u2014 switch on details.code === 'MODIFIER_VALIDATION_FAILED'
3526
+ * first, then iterate details.errors[].
3527
+ */
3528
+ export type ModifierValidationCode =
3529
+ | 'REQUIRED_GROUP_MISSING'
3530
+ | 'MIN_SELECTIONS_NOT_MET'
3531
+ | 'MAX_SELECTIONS_EXCEEDED'
3532
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
3533
+ | 'UNKNOWN_MODIFIER'
3534
+ | 'UNKNOWN_GROUP'
3535
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
3536
+ | 'MODIFIER_NOT_AVAILABLE'
3537
+ | 'NESTED_DEPTH_EXCEEDED'
3538
+ | 'NESTED_REQUIRES_PRODUCT_REF'
3539
+ | 'INVALID_PRICE_DELTA'
3540
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
3541
+
3542
+ export interface ModifierValidationError {
3543
+ code: ModifierValidationCode;
3544
+ message: string;
3545
+ modifierGroupId?: string;
3546
+ modifierId?: string;
3547
+ }
3548
+
3549
+ // Cart DTOs gain optional selections + nestedByModifierId \u2014 see CART_TYPES above.
3550
+ // Add to cart with selections:
3551
+ //
3552
+ // await client.smartAddToCart({
3553
+ // productId,
3554
+ // variantId,
3555
+ // quantity: 1,
3556
+ // selections: [
3557
+ // { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
3558
+ // { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_bacon'] },
3559
+ // ],
3560
+ // });
3561
+ //
3562
+ // The cart line then carries:
3563
+ // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3564
+ // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
3024
3565
  var TYPES_BY_DOMAIN = {
3025
3566
  products: PRODUCTS_TYPES,
3026
3567
  cart: CART_TYPES,
@@ -3029,7 +3570,8 @@ var TYPES_BY_DOMAIN = {
3029
3570
  customers: CUSTOMERS_TYPES,
3030
3571
  payments: PAYMENTS_TYPES,
3031
3572
  helpers: HELPERS_TYPES,
3032
- inquiries: INQUIRIES_TYPES
3573
+ inquiries: INQUIRIES_TYPES,
3574
+ "modifier-groups": MODIFIER_GROUPS_TYPES
3033
3575
  };
3034
3576
  function getTypesByDomain(domain) {
3035
3577
  if (domain === "all") {
@@ -3095,7 +3637,12 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3095
3637
  "reservation-countdown",
3096
3638
  "search-autocomplete-debounce",
3097
3639
  "i18n-set-locale",
3098
- "order-history-full"
3640
+ "order-history-full",
3641
+ "modifier-groups-render",
3642
+ "cart-add-with-selections",
3643
+ "modifier-validation-error-handling",
3644
+ "checkout-price-drift",
3645
+ "cart-item-modifier-display"
3099
3646
  ]).describe("The SDK operation to get a snippet for.")
3100
3647
  };
3101
3648
  var SNIPPETS = {
@@ -3103,7 +3650,10 @@ var SNIPPETS = {
3103
3650
  import { BrainerceClient } from 'brainerce';
3104
3651
 
3105
3652
  export const client = new BrainerceClient({
3106
- connectionId: process.env.BRAINERCE_CONNECTION_ID!, // vc_*
3653
+ // Read either env var name (the new one is preferred; the old one is a soft
3654
+ // alias kept for backwards compatibility \u2014 both are accepted by the SDK).
3655
+ salesChannelId:
3656
+ process.env.BRAINERCE_SALES_CHANNEL_ID! ?? process.env.BRAINERCE_CONNECTION_ID!, // vc_*
3107
3657
  });
3108
3658
 
3109
3659
  // If the store has i18n enabled, set the locale at app start based on
@@ -3523,7 +4073,418 @@ for (const order of orders) {
3523
4073
 
3524
4074
  // All sections above are conditional. Absent data = section not rendered \u2014
3525
4075
  // never show empty placeholders. The create-brainerce-store template's
3526
- // src/components/account/order-history.tsx is the reference implementation.`
4076
+ // src/components/account/order-history.tsx is the reference implementation.`,
4077
+ "modifier-groups-render": `// Render modifier groups on the product detail page (toppings / sauce /
4078
+ // build-your-own). The data lives on product.modifierGroups \u2014 only present
4079
+ // for restaurant / customizable products.
4080
+ import { useState } from 'react';
4081
+ import type { ModifierGroup, Product } from 'brainerce';
4082
+
4083
+ function ModifierGroups({ product }: { product: Product }) {
4084
+ const groups: ModifierGroup[] = product.modifierGroups ?? [];
4085
+ if (groups.length === 0) return null; // not a customizable product
4086
+
4087
+ // Local state: selected modifier IDs per group, in click-order.
4088
+ const [selections, setSelections] = useState<Record<string, string[]>>(() =>
4089
+ buildInitialSelections(groups)
4090
+ );
4091
+
4092
+ return (
4093
+ <>
4094
+ {groups.map((group) => {
4095
+ // PRD \xA77.2.2: max === 0 means "hidden for this variant" \u2014 skip entirely.
4096
+ if (group.max === 0) return null;
4097
+
4098
+ const isSingle = group.selectionType === 'SINGLE';
4099
+ const inputType = isSingle ? 'radio' : 'checkbox';
4100
+ const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
4101
+ const picks = selections[group.id] ?? [];
4102
+ const usedFree = Math.min(picks.length, group.freeQuantity);
4103
+
4104
+ const toggle = (modifierId: string, checked: boolean) => {
4105
+ setSelections((prev) => {
4106
+ const cur = prev[group.id] ?? [];
4107
+ if (isSingle) return { ...prev, [group.id]: checked ? [modifierId] : [] };
4108
+ if (checked) {
4109
+ if (group.max != null && cur.length >= group.max) return prev; // at cap
4110
+ return { ...prev, [group.id]: [...cur, modifierId] };
4111
+ }
4112
+ return { ...prev, [group.id]: cur.filter((id) => id !== modifierId) };
4113
+ });
4114
+ };
4115
+
4116
+ return (
4117
+ <fieldset key={group.id}>
4118
+ <legend>
4119
+ {group.name}{group.required && ' *'}
4120
+ </legend>
4121
+ {group.freeQuantity > 0 && (
4122
+ <p>{usedFree} of {group.freeQuantity} free</p>
4123
+ )}
4124
+ {sorted.map((m) => (
4125
+ <label key={m.id}>
4126
+ <input
4127
+ type={inputType}
4128
+ name={\`mg-\${group.id}\`}
4129
+ value={m.id}
4130
+ checked={picks.includes(m.id)}
4131
+ disabled={!m.available}
4132
+ onChange={(e) => toggle(m.id, e.target.checked)}
4133
+ />
4134
+ {m.name}
4135
+ {parseFloat(m.priceDelta) !== 0 && (
4136
+ <span> {parseFloat(m.priceDelta) > 0 ? '+' : ''}{m.priceDelta}</span>
4137
+ )}
4138
+ {!m.available && <span> (Sold out)</span>}
4139
+ </label>
4140
+ ))}
4141
+ </fieldset>
4142
+ );
4143
+ })}
4144
+ </>
4145
+ );
4146
+ }
4147
+
4148
+ // Initial state: prefer per-attach defaultModifierIds; fall back to
4149
+ // modifier.isDefault flags. Filter sold-out modifiers.
4150
+ function buildInitialSelections(groups: ModifierGroup[]): Record<string, string[]> {
4151
+ const out: Record<string, string[]> = {};
4152
+ for (const group of groups) {
4153
+ if (group.max === 0) continue;
4154
+ const fromAttach = group.defaultModifierIds ?? [];
4155
+ const fromIsDefault = group.modifiers
4156
+ .filter((m) => m.isDefault && m.available)
4157
+ .map((m) => m.id);
4158
+ const merged =
4159
+ fromAttach.length > 0
4160
+ ? fromAttach.filter((id) => group.modifiers.some((m) => m.id === id && m.available))
4161
+ : fromIsDefault;
4162
+ const capped = group.selectionType === 'SINGLE' ? merged.slice(0, 1) : merged;
4163
+ if (capped.length > 0) out[group.id] = capped;
4164
+ }
4165
+ return out;
4166
+ }
4167
+
4168
+ // PRICE-DELTA RULES:
4169
+ // - "5.00" \u2192 +$5 added to unit price
4170
+ // - "-2.00" \u2192 downsell: subtracts $2; never consumes a free slot
4171
+ // - "0.00" \u2192 free option; render no price label
4172
+ // Server enforces unitPrice >= 0; rejects negative deltas combined with
4173
+ // referencedProductId. Do NOT compute the line total client-side \u2014 the
4174
+ // server runs free-allocation and returns cart.items[i].unitPrice.
4175
+
4176
+ `,
4177
+ "cart-add-with-selections": `// Pass modifier-group selections on add-to-cart. The server validates
4178
+ // against the effective rules and computes the final unitPrice (base +
4179
+ // paid modifiers, after the free-allocation policy runs).
4180
+ import { client } from './brainerce';
4181
+ import type { ModifierSelection } from 'brainerce';
4182
+
4183
+ async function addPizzaToCart(
4184
+ productId: string,
4185
+ variantId: string,
4186
+ selectionsByGroup: Record<string, string[]>
4187
+ ) {
4188
+ // Adapter: shape used in component state \u2192 wire format the SDK accepts.
4189
+ const selections: ModifierSelection[] = Object.entries(selectionsByGroup)
4190
+ .filter(([, modifierIds]) => modifierIds.length > 0)
4191
+ .map(([modifierGroupId, modifierIds]) => ({ modifierGroupId, modifierIds }));
4192
+
4193
+ // modifierIds is in CLICK-ORDER \u2014 used by the SELECTION_ORDER free-allocation
4194
+ // policy. Don't sort it; preserve the order the customer clicked.
4195
+
4196
+ const cart = await client.smartAddToCart({
4197
+ productId,
4198
+ variantId,
4199
+ quantity: 1,
4200
+ selections,
4201
+ });
4202
+
4203
+ // Read the snapshot back off the new cart line.
4204
+ const line = cart.items[cart.items.length - 1];
4205
+ // line.modifiers \u2192 CartItemModifierLine[] with { modifierId, name, priceDelta, freeApplied }
4206
+ // line.modifiersTotal \u2192 decimal string of paid (non-free) deltas
4207
+ // line.unitPrice \u2192 final unit price including all paid modifiers
4208
+ console.log('Free applied:', line.modifiers?.filter((m) => m.freeApplied).map((m) => m.name));
4209
+ }
4210
+
4211
+ // EDITING SELECTIONS LATER (PRD \xA77.2.3 \u2014 idempotent replacement):
4212
+ // PATCH the cart item with a fresh selections array. The server deletes ALL
4213
+ // existing CartItemModifier rows and recreates them in the same transaction.
4214
+ // To leave selections untouched (e.g., quantity-only update), omit them.
4215
+ async function changeToppings(cartId: string, itemId: string, newToppingIds: string[]) {
4216
+ await client.updateCartItem(cartId, itemId, {
4217
+ quantity: 1,
4218
+ selections: [{ modifierGroupId: 'mg_toppings', modifierIds: newToppingIds }],
4219
+ });
4220
+ }
4221
+
4222
+ // NESTED COMBOS (depth \u2264 3): when a picked modifier carries
4223
+ // referencedProductId, fetch that product's own modifierGroups, collect the
4224
+ // nested selections, and pass them keyed by the PARENT modifier id.
4225
+ async function addCombo(productId: string, mainBurger: string) {
4226
+ await client.smartAddToCart({
4227
+ productId,
4228
+ quantity: 1,
4229
+ selections: [
4230
+ { modifierGroupId: 'mg_main', modifierIds: [mainBurger] }, // the burger
4231
+ { modifierGroupId: 'mg_drink', modifierIds: ['m_cola'] },
4232
+ ],
4233
+ nestedByModifierId: {
4234
+ [mainBurger]: [
4235
+ { modifierGroupId: 'mg_doneness', modifierIds: ['m_medium'] },
4236
+ { modifierGroupId: 'mg_cheese', modifierIds: ['m_cheddar'] },
4237
+ ],
4238
+ },
4239
+ });
4240
+ }`,
4241
+ "modifier-validation-error-handling": `// Surface MODIFIER_VALIDATION_FAILED to the user. The SDK throws
4242
+ // BrainerceError on HTTP 400; the structured envelope is on .details.
4243
+ import { client } from './brainerce';
4244
+ import type { ModifierSelection } from 'brainerce';
4245
+
4246
+ interface ModifierValidationError {
4247
+ code:
4248
+ | 'REQUIRED_GROUP_MISSING'
4249
+ | 'MIN_SELECTIONS_NOT_MET'
4250
+ | 'MAX_SELECTIONS_EXCEEDED'
4251
+ | 'SINGLE_GROUP_MULTIPLE_PICKS'
4252
+ | 'UNKNOWN_MODIFIER'
4253
+ | 'UNKNOWN_GROUP'
4254
+ | 'MODIFIER_DISABLED_FOR_VARIANT'
4255
+ | 'MODIFIER_NOT_AVAILABLE'
4256
+ | 'NESTED_DEPTH_EXCEEDED'
4257
+ | 'NESTED_REQUIRES_PRODUCT_REF'
4258
+ | 'INVALID_PRICE_DELTA'
4259
+ | 'MODIFIER_PRICE_FLOOR_VIOLATED';
4260
+ message: string;
4261
+ modifierGroupId?: string;
4262
+ modifierId?: string;
4263
+ }
4264
+
4265
+ async function tryAddToCart(productId: string, selections: ModifierSelection[]) {
4266
+ try {
4267
+ await client.smartAddToCart({ productId, quantity: 1, selections });
4268
+ return { ok: true as const };
4269
+ } catch (err) {
4270
+ const e = err as {
4271
+ statusCode?: number;
4272
+ details?: { code?: string; errors?: ModifierValidationError[] };
4273
+ };
4274
+
4275
+ if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
4276
+ // Surface each issue inline. groupId / modifierId let you highlight the
4277
+ // specific control the customer needs to fix.
4278
+ const issues = e.details.errors ?? [];
4279
+ const messages = issues.map((i) => formatIssue(i));
4280
+ return { ok: false as const, issues, messages };
4281
+ }
4282
+
4283
+ // Some other error (network, 500, etc.) \u2014 re-throw to a generic handler.
4284
+ throw err;
4285
+ }
4286
+ }
4287
+
4288
+ function formatIssue(issue: ModifierValidationError): string {
4289
+ switch (issue.code) {
4290
+ case 'REQUIRED_GROUP_MISSING':
4291
+ return 'Please pick at least one option from this group.';
4292
+ case 'MIN_SELECTIONS_NOT_MET':
4293
+ case 'MAX_SELECTIONS_EXCEEDED':
4294
+ case 'SINGLE_GROUP_MULTIPLE_PICKS':
4295
+ return issue.message; // server's message already says "Pick at least N" / "Pick at most N"
4296
+ case 'UNKNOWN_MODIFIER':
4297
+ case 'UNKNOWN_GROUP':
4298
+ case 'MODIFIER_DISABLED_FOR_VARIANT':
4299
+ case 'MODIFIER_NOT_AVAILABLE':
4300
+ // The catalog moved under us \u2014 refetch the product and ask the customer
4301
+ // to re-pick. These codes mean the option simply isn't valid anymore.
4302
+ return 'This option is no longer available \u2014 please refresh.';
4303
+ case 'NESTED_DEPTH_EXCEEDED':
4304
+ case 'NESTED_REQUIRES_PRODUCT_REF':
4305
+ return issue.message; // bug in your renderer \u2014 never go past 3 levels
4306
+ case 'INVALID_PRICE_DELTA':
4307
+ return issue.message; // shouldn't happen for SDK callers \u2014 server-validated on save
4308
+ case 'MODIFIER_PRICE_FLOOR_VIOLATED':
4309
+ // The server reports a generic message \u2014 internals never leak. Show a
4310
+ // friendly error and let the customer remove a downsell.
4311
+ return 'Cannot apply more discounts on this item.';
4312
+ }
4313
+ }
4314
+
4315
+ // CLIENT-SIDE PRE-FLIGHT (UX):
4316
+ // You can mirror these checks before calling addToCart to give faster
4317
+ // feedback, but the SERVER is authoritative. Always treat the 400 envelope
4318
+ // as the source of truth.
4319
+ function preflightSelections(
4320
+ groups: { id: string; name: string; min: number; max?: number | null; required: boolean; selectionType: 'SINGLE' | 'MULTIPLE'; }[],
4321
+ selections: Record<string, string[]>
4322
+ ): string | null {
4323
+ for (const g of groups) {
4324
+ if (g.max === 0) continue; // disabled-for-variant
4325
+ const picks = selections[g.id] ?? [];
4326
+ if (g.required && picks.length === 0) return \`\${g.name} is required\`;
4327
+ if (picks.length < g.min) return \`Pick at least \${g.min} from \${g.name}\`;
4328
+ if (g.max != null && picks.length > g.max) return \`Pick at most \${g.max} from \${g.name}\`;
4329
+ if (g.selectionType === 'SINGLE' && picks.length > 1) return \`Only one option allowed in \${g.name}\`;
4330
+ }
4331
+ return null;
4332
+ }`,
4333
+ "checkout-price-drift": `// PRICE_DRIFT \u2014 a product's price changed between add-to-cart and checkout.
4334
+ // The server returns HTTP 400 with code "PRICE_DRIFT" when it detects that
4335
+ // the stored unitPrice no longer matches the live price.
4336
+ //
4337
+ // Strategy: catch the error \u2192 show "prices updated" dialog \u2192
4338
+ // call refreshCartSnapshots() to re-snapshot all live prices \u2192
4339
+ // retry createCheckout once.
4340
+
4341
+ import { client } from './brainerce-client';
4342
+
4343
+ interface CheckoutOptions {
4344
+ cartId: string;
4345
+ shippingAddress: object;
4346
+ shippingMethodId: string;
4347
+ paymentProviderId: string;
4348
+ }
4349
+
4350
+ async function createCheckoutSafe(opts: CheckoutOptions) {
4351
+ try {
4352
+ return await client.createCheckout({
4353
+ cartId: opts.cartId,
4354
+ shippingAddress: opts.shippingAddress,
4355
+ shippingMethodId: opts.shippingMethodId,
4356
+ paymentProviderId: opts.paymentProviderId,
4357
+ });
4358
+ } catch (err: unknown) {
4359
+ if (!isApiError(err, 'PRICE_DRIFT')) throw err;
4360
+
4361
+ // Prices changed \u2014 refresh snapshots then retry once.
4362
+ // refreshCartSnapshots updates every cart item's unitPrice to the current
4363
+ // live price (base price + any modifier deltas) so the next checkout call
4364
+ // will pass the drift guard.
4365
+ await client.refreshCartSnapshots(opts.cartId);
4366
+
4367
+ // After refreshing, re-fetch the cart so your UI shows the updated prices
4368
+ // before you retry, giving the customer a chance to review.
4369
+ const updatedCart = await client.getCart(opts.cartId);
4370
+
4371
+ // Signal to the UI layer that prices changed so it can show a dialog.
4372
+ throw Object.assign(new Error('PRICES_UPDATED'), {
4373
+ code: 'PRICES_UPDATED',
4374
+ updatedCart,
4375
+ });
4376
+ }
4377
+ }
4378
+
4379
+ function isApiError(err: unknown, code: string): boolean {
4380
+ return (
4381
+ typeof err === 'object' &&
4382
+ err !== null &&
4383
+ 'code' in err &&
4384
+ (err as { code: string }).code === code
4385
+ );
4386
+ }
4387
+
4388
+ // --- UI integration example (framework-neutral) ---
4389
+ //
4390
+ // async function handlePlaceOrder() {
4391
+ // try {
4392
+ // const checkout = await createCheckoutSafe({ cartId, ... });
4393
+ // router.push(\`/order-confirmation?checkoutId=\${checkout.id}\`);
4394
+ // } catch (err: unknown) {
4395
+ // if (isApiError(err, 'PRICES_UPDATED')) {
4396
+ // const { updatedCart } = err as { updatedCart: Cart };
4397
+ // showPricesUpdatedDialog(updatedCart); // show diff, let user confirm
4398
+ // return;
4399
+ // }
4400
+ // showGenericError(err);
4401
+ // }
4402
+ // }
4403
+ //
4404
+ // The dialog should:
4405
+ // 1. Show which items changed price (compare old vs new unitPrice)
4406
+ // 2. Offer "Continue with new prices" (calls createCheckoutSafe again)
4407
+ // and "Go back to cart" (returns to cart page)
4408
+ // 3. NOT silently retry \u2014 the customer must acknowledge the price change.`,
4409
+ "cart-item-modifier-display": `// Rendering cart items that have modifier selections.
4410
+ // Each cart item has a \`modifiers\` array \u2014 each entry records the modifier
4411
+ // name, the price delta at time of add-to-cart, and whether it was free
4412
+ // (inside the group's freeQuantity allowance).
4413
+ //
4414
+ // Typical display:
4415
+ // Margherita \u20AA45.00
4416
+ // Extra cheese +\u20AA5.00
4417
+ // Mushrooms free
4418
+ // No onions \u2014
4419
+ // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
4420
+ // Base \u20AA45.00 + Modifiers \u20AA5.00 = \u20AA50.00
4421
+
4422
+ import { formatPrice } from 'brainerce';
4423
+
4424
+ interface CartItemModifier {
4425
+ modifierId: string;
4426
+ name: string;
4427
+ priceDeltaAtTime: number; // in store currency units, e.g. 5.00
4428
+ freeApplied: boolean; // true when inside the group's freeQuantity
4429
+ }
4430
+
4431
+ interface CartItem {
4432
+ id: string;
4433
+ name: string;
4434
+ unitPrice: number; // base + all chargeable modifier deltas, as stored
4435
+ quantity: number;
4436
+ modifiers?: CartItemModifier[];
4437
+ currency: string; // e.g. 'ILS', 'USD'
4438
+ }
4439
+
4440
+ function renderCartItem(item: CartItem): string {
4441
+ const currency = item.currency;
4442
+ const lines: string[] = [];
4443
+
4444
+ lines.push(\`\${item.name} \${formatPrice(item.unitPrice, { currency })}\`);
4445
+
4446
+ const chargeableModifiers = (item.modifiers ?? []).filter(
4447
+ (m) => !m.freeApplied && m.priceDeltaAtTime !== 0
4448
+ );
4449
+ const freeModifiers = (item.modifiers ?? []).filter((m) => m.freeApplied);
4450
+ const zeroModifiers = (item.modifiers ?? []).filter(
4451
+ (m) => !m.freeApplied && m.priceDeltaAtTime === 0
4452
+ );
4453
+
4454
+ for (const m of chargeableModifiers) {
4455
+ const sign = m.priceDeltaAtTime > 0 ? '+' : '';
4456
+ lines.push(\` \${m.name} \${sign}\${formatPrice(m.priceDeltaAtTime, { currency })}\`);
4457
+ }
4458
+ for (const m of freeModifiers) {
4459
+ lines.push(\` \${m.name} free\`);
4460
+ }
4461
+ for (const m of zeroModifiers) {
4462
+ lines.push(\` \${m.name} \u2014\`);
4463
+ }
4464
+
4465
+ // Price breakdown: only show when there are chargeable modifiers
4466
+ const modifiersTotal = chargeableModifiers.reduce(
4467
+ (sum, m) => sum + m.priceDeltaAtTime,
4468
+ 0
4469
+ );
4470
+ if (modifiersTotal !== 0) {
4471
+ // unitPrice already includes modifiers \u2014 derive base for display only
4472
+ const basePrice = item.unitPrice - modifiersTotal;
4473
+ const base = formatPrice(basePrice, { currency }) as string;
4474
+ const mods = formatPrice(modifiersTotal, { currency }) as string;
4475
+ const total = formatPrice(item.unitPrice, { currency }) as string;
4476
+ lines.push(\`Base \${base} + Modifiers \${mods} = \${total}\`);
4477
+ }
4478
+
4479
+ return lines.join('\\n');
4480
+ }
4481
+
4482
+ // IMPORTANT: unitPrice already includes all chargeable modifier deltas.
4483
+ // Do NOT add modifier prices on top of unitPrice when computing line totals \u2014
4484
+ // multiply unitPrice \xD7 quantity directly.
4485
+ function lineTotal(item: CartItem): number {
4486
+ return item.unitPrice * item.quantity;
4487
+ }`
3527
4488
  };
3528
4489
  async function handleGetCodeExample(args) {
3529
4490
  const snippet = SNIPPETS[args.operation];
@@ -3639,13 +4600,27 @@ function getCandidateApiUrls() {
3639
4600
 
3640
4601
  // src/tools/get-store-info.ts
3641
4602
  var GET_STORE_INFO_NAME = "get-store-info";
3642
- var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a connection ID. Returns the channel display name (what the user sees in their dashboard), parent store name, currency, and language. Use this to personalize the store being built \u2014 prefer the channel name for user-facing text since a single Brainerce store can have multiple sales channels.";
4603
+ var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a sales channel ID. Returns the channel display name (what the user sees in their dashboard), parent store name, currency, and language. Use this to personalize the store being built \u2014 prefer the channel name for user-facing text since a single Brainerce store can have multiple sales channels.";
3643
4604
  var GET_STORE_INFO_SCHEMA = {
3644
- connectionId: z4.string().describe("Vibe-coded connection ID (starts with vc_)")
4605
+ salesChannelId: z4.string().optional().describe("Sales channel ID (starts with vc_)"),
4606
+ /** @deprecated alias of salesChannelId */
4607
+ connectionId: z4.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3645
4608
  };
3646
4609
  async function handleGetStoreInfo(args) {
4610
+ const id = args.salesChannelId ?? args.connectionId;
4611
+ if (!id) {
4612
+ return {
4613
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4614
+ isError: true
4615
+ };
4616
+ }
4617
+ if (!args.salesChannelId && args.connectionId) {
4618
+ console.warn(
4619
+ "get-store-info: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4620
+ );
4621
+ }
3647
4622
  try {
3648
- const resolved = await resolveStoreInfo(args.connectionId, getCandidateApiUrls());
4623
+ const resolved = await resolveStoreInfo(id, getCandidateApiUrls());
3649
4624
  return {
3650
4625
  content: [
3651
4626
  {
@@ -3658,7 +4633,8 @@ async function handleGetStoreInfo(args) {
3658
4633
  storeName: resolved.info.storeName,
3659
4634
  currency: resolved.info.currency,
3660
4635
  language: resolved.info.language,
3661
- connectionId: args.connectionId,
4636
+ salesChannelId: id,
4637
+ connectionId: id,
3662
4638
  apiBaseUrl: resolved.apiBaseUrl
3663
4639
  },
3664
4640
  null,
@@ -3743,9 +4719,11 @@ async function resolveStoreCapabilities(connectionId, candidateUrls) {
3743
4719
 
3744
4720
  // src/tools/get-store-capabilities.ts
3745
4721
  var GET_STORE_CAPABILITIES_NAME = "get-store-capabilities";
3746
- var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a vibe-coded connection. Returns what payment providers, OAuth, shipping, discounts, and other features are set up. Use this to discover what your store supports and what pages/components to build.";
4722
+ var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a sales channel. Returns what payment providers, OAuth, shipping, discounts, and other features are set up. Use this to discover what your store supports and what pages/components to build.";
3747
4723
  var GET_STORE_CAPABILITIES_SCHEMA = {
3748
- connectionId: z5.string().describe("Vibe-coded connection ID (starts with vc_)")
4724
+ salesChannelId: z5.string().optional().describe("Sales channel ID (starts with vc_)"),
4725
+ /** @deprecated alias of salesChannelId */
4726
+ connectionId: z5.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
3749
4727
  };
3750
4728
  function formatCapabilities(caps) {
3751
4729
  const lines = [];
@@ -3858,15 +4836,27 @@ function formatCapabilities(caps) {
3858
4836
  }
3859
4837
  if (suggestions.length === 0) {
3860
4838
  suggestions.push(
3861
- "Start by building the required features. Use get-required-features with this connectionId for the checklist."
4839
+ "Start by building the required features. Use get-required-features with this salesChannelId for the checklist."
3862
4840
  );
3863
4841
  }
3864
4842
  suggestions.forEach((s) => lines.push(`- ${s}`));
3865
4843
  return lines.join("\n");
3866
4844
  }
3867
4845
  async function handleGetStoreCapabilities(args) {
4846
+ const id = args.salesChannelId ?? args.connectionId;
4847
+ if (!id) {
4848
+ return {
4849
+ content: [{ type: "text", text: "Error: salesChannelId is required" }],
4850
+ isError: true
4851
+ };
4852
+ }
4853
+ if (!args.salesChannelId && args.connectionId) {
4854
+ console.warn(
4855
+ "get-store-capabilities: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
4856
+ );
4857
+ }
3868
4858
  try {
3869
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
4859
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
3870
4860
  return {
3871
4861
  content: [{ type: "text", text: formatCapabilities(resolved.capabilities) }]
3872
4862
  };
@@ -3971,7 +4961,7 @@ var RULES = {
3971
4961
  tokens: {
3972
4962
  title: "Auth tokens & BFF pattern",
3973
4963
  body: `- NEVER store customer auth tokens in \`localStorage\` directly from client code. Use a Backend-For-Frontend proxy: the server receives the token, sets an HttpOnly cookie, and the client reads session state from an endpoint like \`/api/auth/me\`.
3974
- - NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`connectionId\` or storefront endpoints.
4964
+ - NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`salesChannelId\` (or the deprecated \`connectionId\` alias) or storefront endpoints.
3975
4965
  - OAuth callbacks arrive with the token in URL params. Extract it SERVER-side and exchange it for a session cookie before redirecting to the app. Do not let the token land in browser history.
3976
4966
  - On logout, clear the BFF session server-side. A client-only logout that forgets to tell the server leaves an active session on the server until it expires.`
3977
4967
  },
@@ -4264,18 +5254,20 @@ ${flow.body}`
4264
5254
  // src/tools/get-required-features.ts
4265
5255
  import { z as z9 } from "zod";
4266
5256
  var GET_REQUIRED_FEATURES_NAME = "get-required-features";
4267
- var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a connectionId to tune the checklist to the live store; without it, returns the generic complete-store checklist.";
5257
+ var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a salesChannelId to tune the checklist to the live store; without it, returns the generic complete-store checklist.";
4268
5258
  var GET_REQUIRED_FEATURES_SCHEMA = {
4269
- connectionId: z9.string().optional().describe(
4270
- "Vibe-coded connection ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
4271
- )
5259
+ salesChannelId: z9.string().optional().describe(
5260
+ "Sales channel ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
5261
+ ),
5262
+ /** @deprecated alias of salesChannelId */
5263
+ connectionId: z9.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
4272
5264
  };
4273
5265
  var FEATURES = [
4274
5266
  {
4275
5267
  id: "browse-products",
4276
5268
  title: "Browse, filter, and search products",
4277
- description: "Users can list products with pagination, apply category / price / attribute filters, sort by name / price / newest, and run a search with autocomplete. Must handle empty states and loading states.",
4278
- sdk: "client.getProducts({ page, limit, filters, sort }), client.searchProducts(query)",
5269
+ description: "Users can list products with pagination, apply category / price / attribute / custom-field filters, sort by name / price / newest, and run a search with autocomplete. Custom-field filters surface metafield definitions whose filterable=true (SELECT, MULTI_SELECT, BOOLEAN). Must handle empty states and loading states.",
5270
+ sdk: "client.getProducts({ page, limit, filters, sort, metafields }), client.getPublicMetafieldDefinitions(), client.searchProducts(query)",
4279
5271
  mandatory: "mandatory"
4280
5272
  },
4281
5273
  {
@@ -4490,10 +5482,16 @@ function renderCapabilitiesSummary(caps) {
4490
5482
  return lines.join("\n");
4491
5483
  }
4492
5484
  async function handleGetRequiredFeatures(args) {
5485
+ const id = args.salesChannelId ?? args.connectionId;
5486
+ if (!args.salesChannelId && args.connectionId) {
5487
+ console.warn(
5488
+ "get-required-features: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
5489
+ );
5490
+ }
4493
5491
  let caps = null;
4494
- if (args.connectionId) {
5492
+ if (id) {
4495
5493
  try {
4496
- const resolved = await resolveStoreCapabilities(args.connectionId, getCandidateApiUrls());
5494
+ const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
4497
5495
  caps = resolved.capabilities;
4498
5496
  } catch {
4499
5497
  caps = null;
@@ -4505,11 +5503,11 @@ async function handleGetRequiredFeatures(args) {
4505
5503
  );
4506
5504
  if (caps) {
4507
5505
  sections.push(renderCapabilitiesSummary(caps));
4508
- } else if (args.connectionId) {
5506
+ } else if (id) {
4509
5507
  sections.push(
4510
5508
  `## Live store capabilities
4511
5509
 
4512
- Could not fetch live capabilities for \`${args.connectionId}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
5510
+ Could not fetch live capabilities for \`${id}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
4513
5511
  );
4514
5512
  }
4515
5513
  sections.push("## Features");