@brainerce/mcp-server 3.6.0 → 3.8.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/bin/stdio.js CHANGED
@@ -922,6 +922,175 @@ function ProductPage({ product, storeInfo }: { product: Product; storeInfo: Stor
922
922
  }
923
923
  \`\`\`
924
924
 
925
+ ### Variant Attribute Selector with Swatches (color + size **mix**)
926
+
927
+ The simple text-button picker above works, but loses the merchant-configured
928
+ **swatch metadata**. A single product often mixes one attribute that should
929
+ render as **color swatches** (e.g. \`Color\`) and another that should render
930
+ as **text buttons** (e.g. \`Size\`). The product response includes everything
931
+ you need:
932
+
933
+ - \`product.productAttributeOptions[]\` \u2014 the swatch definitions: \`attribute.name\`,
934
+ \`attribute.displayType\` (the \`AttributeDisplayType\` enum: \`DEFAULT\` | \`COLOR_SWATCH\` | \`IMAGE_SWATCH\` | \`MIXED_SWATCH\`),
935
+ \`attributeOption.name\`, \`swatchColor\` (hex), \`swatchColor2\` (hex \u2014 used for dual-color swatches
936
+ like Black & White), \`swatchImageUrl\` (for fabric / pattern thumbnails).
937
+ \`MIXED_SWATCH\` means each option in the group can independently pick image OR color
938
+ (the merchant decides per option). Treat any unrecognized value as \`DEFAULT\`.
939
+ - \`variant.attributes\` \u2014 the selected value per attribute on each variant.
940
+
941
+ Use \`getProductSwatches(product)\` to get a render-ready, grouped structure:
942
+
943
+ \`\`\`typescript
944
+ import { getProductSwatches } from 'brainerce';
945
+
946
+ const groups = getProductSwatches(product);
947
+ // [
948
+ // { attributeName: 'color', displayType: 'COLOR_SWATCH', options: [
949
+ // { name: 'Full Color', swatchColor: '#1D9435', swatchColor2: null, swatchImageUrl: null },
950
+ // { name: 'Black & White', swatchColor: '#000000', swatchColor2: '#FFFFFF', swatchImageUrl: null },
951
+ // ]},
952
+ // { attributeName: 'size', displayType: 'DEFAULT', options: [
953
+ // { name: '16" \xD7 20"' }, { name: '24" \xD7 32"' }, { name: '36" \xD7 48"' },
954
+ // ]},
955
+ // ]
956
+ \`\`\`
957
+
958
+ Render one branch per \`displayType\`. The same loop handles all-swatch, all-text,
959
+ and the mix case:
960
+
961
+ \`\`\`typescript
962
+ function VariantPicker({
963
+ product,
964
+ selections,
965
+ onSelect,
966
+ }: {
967
+ product: Product;
968
+ selections: Record<string, string>; // { color: 'Full Color', size: '24" \xD7 32"' }
969
+ onSelect: (attrName: string, value: string) => void;
970
+ }) {
971
+ const groups = getProductSwatches(product);
972
+ if (groups.length === 0) return null;
973
+
974
+ return (
975
+ <div className="space-y-4">
976
+ {groups.map((group) => (
977
+ <div key={group.attributeName}>
978
+ <label className="block mb-2 text-sm font-medium">
979
+ {group.attributeName}: <span className="text-gray-500">{selections[group.attributeName] ?? ''}</span>
980
+ </label>
981
+ <div className="flex flex-wrap gap-2">
982
+ {group.options.map((opt) => {
983
+ const isSelected = selections[group.attributeName] === opt.name;
984
+
985
+ // COLOR_SWATCH \u2014 round button; dual-color uses a 50/50 gradient.
986
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
987
+ const bg = opt.swatchColor2
988
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
989
+ : opt.swatchColor;
990
+ return (
991
+ <button
992
+ key={opt.name}
993
+ type="button"
994
+ title={opt.name}
995
+ aria-pressed={isSelected}
996
+ onClick={() => onSelect(group.attributeName, opt.name)}
997
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
998
+ style={{ background: bg }}
999
+ />
1000
+ );
1001
+ }
1002
+
1003
+ // IMAGE_SWATCH \u2014 square thumbnail (fabric/pattern preview).
1004
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
1005
+ return (
1006
+ <button
1007
+ key={opt.name}
1008
+ type="button"
1009
+ aria-pressed={isSelected}
1010
+ onClick={() => onSelect(group.attributeName, opt.name)}
1011
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1012
+ >
1013
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1014
+ </button>
1015
+ );
1016
+ }
1017
+
1018
+ // MIXED_SWATCH \u2014 each option is independently image OR color (image wins if present).
1019
+ if (group.displayType === 'MIXED_SWATCH') {
1020
+ if (opt.swatchImageUrl) {
1021
+ return (
1022
+ <button
1023
+ key={opt.name}
1024
+ type="button"
1025
+ aria-pressed={isSelected}
1026
+ onClick={() => onSelect(group.attributeName, opt.name)}
1027
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1028
+ >
1029
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1030
+ </button>
1031
+ );
1032
+ }
1033
+ if (opt.swatchColor) {
1034
+ const bg = opt.swatchColor2
1035
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
1036
+ : opt.swatchColor;
1037
+ return (
1038
+ <button
1039
+ key={opt.name}
1040
+ type="button"
1041
+ title={opt.name}
1042
+ aria-pressed={isSelected}
1043
+ onClick={() => onSelect(group.attributeName, opt.name)}
1044
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
1045
+ style={{ background: bg }}
1046
+ />
1047
+ );
1048
+ }
1049
+ // option has neither image nor color \u2192 fall through to text button below.
1050
+ }
1051
+
1052
+ // DEFAULT (or any swatch type missing its data) \u2014 plain text button.
1053
+ return (
1054
+ <button
1055
+ key={opt.name}
1056
+ type="button"
1057
+ aria-pressed={isSelected}
1058
+ onClick={() => onSelect(group.attributeName, opt.name)}
1059
+ className={\`rounded border px-3 py-1.5 text-sm \${isSelected ? 'bg-black text-white border-black' : 'border-gray-300 hover:border-black'}\`}
1060
+ >
1061
+ {opt.name}
1062
+ </button>
1063
+ );
1064
+ })}
1065
+ </div>
1066
+ </div>
1067
+ ))}
1068
+ </div>
1069
+ );
1070
+ }
1071
+ \`\`\`
1072
+
1073
+ Wire it up in the product page: keep \`selections\` in state, find the matching
1074
+ variant after each pick, and update price / image / stock from it.
1075
+
1076
+ \`\`\`typescript
1077
+ const [selections, setSelections] = useState<Record<string, string>>({});
1078
+
1079
+ const matchedVariant = useMemo(() => (
1080
+ product.variants?.find((v) =>
1081
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
1082
+ ) ?? null
1083
+ ), [product.variants, selections]);
1084
+
1085
+ // Greying-out unavailable combinations: for each candidate value, run
1086
+ // the same find() and check \`inventory.canPurchase\`. Disable the button
1087
+ // if no purchasable variant exists under that selection.
1088
+ \`\`\`
1089
+
1090
+ **i18n:** \`getProductSwatches\` returns translated \`attributeName\` and
1091
+ \`option.name\` automatically when \`client.setLocale()\` is active. No
1092
+ client-side overlay needed. Swatch colors are language-agnostic.
1093
+
925
1094
  ### Description Rendering (handles HTML vs text)
926
1095
 
927
1096
  \`\`\`typescript
@@ -1556,17 +1725,28 @@ Allergens (informational chips), scheduled availability windows, nested combos (
1556
1725
  function getProductReviewsSection() {
1557
1726
  return `## Product Reviews (\u2605 ratings + JSON-LD for SEO)
1558
1727
 
1559
- Reviews publish immediately on submit. Merchants hide individual reviews via the admin surface \u2014 no PENDING queue.
1728
+ **Purchaser-only.** Only authenticated customers who purchased the product can submit. Each customer writes one review per product and can edit/delete it. Reviews publish immediately \u2014 no PENDING queue.
1560
1729
 
1561
1730
  \`\`\`typescript
1562
- // PDP \u2014 list visible reviews
1563
- const { data, meta } = await client.listProductReviews(productId, { page: 1, limit: 20 });
1564
- data.forEach(r => render(r.authorName, r.rating, r.body, r.verifiedPurchase));
1731
+ // PDP \u2014 list visible reviews (public)
1732
+ const { data } = await getClient().listProductReviews(productId, { page: 1, limit: 20 });
1733
+
1734
+ // Decide which UI to render for the current customer
1735
+ getClient().setCustomerToken(authToken); // after login
1736
+ const { eligible, reason, myReview } = await getClient().getMyProductReview(productId);
1737
+
1738
+ if (!eligible) {
1739
+ // reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found'
1740
+ // \u2192 "only customers who purchased this product can leave a review"
1741
+ } else if (myReview) {
1742
+ // \u2192 edit form prefilled with myReview.rating + myReview.body
1743
+ } else {
1744
+ // \u2192 submit form (rating + body only \u2014 name/email come from customer profile)
1745
+ }
1565
1746
 
1566
- // PDP \u2014 submit form
1567
- await client.submitProductReview(productId, {
1568
- authorName, authorEmail, rating: 5, body,
1569
- });
1747
+ await getClient().submitProductReview(productId, { rating: 5, body: 'Loved it!' });
1748
+ await getClient().updateMyProductReview(productId, { rating: 4, body: 'Updated.' });
1749
+ await getClient().deleteMyProductReview(productId); // can submit a new one after
1570
1750
  \`\`\`
1571
1751
 
1572
1752
  Each \`Product\` carries denormalized rollups: \`product.avgRating\`, \`product.reviewCount\`. Use these on PLP cards.
@@ -1595,9 +1775,10 @@ const productJsonLd = {
1595
1775
 
1596
1776
  ### Rules
1597
1777
  - Rating must be an integer 1-5 (DB constraint).
1598
- - Duplicate from same email \u2192 409 Conflict.
1599
- - Submit endpoint is throttled to 3 / 60s / IP \u2014 surface a friendly "please wait" on 429.
1600
- - \`verifiedPurchase\` is derived server-side from DELIVERED orders \u2014 DO NOT try to set it.
1778
+ - Customer must be logged in AND have purchased the product (\`SHIPPED+\` for physical, \`PAID+\` for downloadable).
1779
+ - One review per (productId, customerId). Duplicate submit \u2192 409 \u2014 use updateMyProductReview instead.
1780
+ - Submit throttled 3 / 60s / IP; edit/delete 5 / 60s / IP.
1781
+ - \`verifiedPurchase\` is always true for customer-submitted reviews.
1601
1782
  - Stores with \`reviewsEnabled = false\` return 403 on storefront endpoints.`;
1602
1783
  }
1603
1784
  function getInventorySection() {
@@ -2019,9 +2200,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
2019
2200
  const client = getServerClient();
2020
2201
  client.setLocale(locale);
2021
2202
  const product = await client.getProductBySlug(slug);
2203
+ // NEVER feed raw HTML into <meta name="description"> \u2014 product.description
2204
+ // is often rich-text HTML. Strip tags first, then truncate on a word
2205
+ // boundary. See buildMetaDescription() in lib/seo.ts.
2022
2206
  return {
2023
2207
  title: product.seoTitle || product.name,
2024
- description: product.seoDescription || product.description?.slice(0, 160),
2208
+ description: product.seoDescription || buildMetaDescription(product.description) || product.name,
2025
2209
  };
2026
2210
  }
2027
2211
  \`\`\`
@@ -2137,11 +2321,25 @@ Because the backend already overlays everything, UI code is just:
2137
2321
 
2138
2322
  ### RTL handling
2139
2323
 
2140
- For RTL locales (\`he\`, \`ar\`), set \`<html dir="rtl">\` in the root layout and
2141
- let flexbox reverse automatically. Do NOT add \`flex-row-reverse\` on top of
2142
- \`dir="rtl"\` \u2014 that's a double-swap. DO swap directional icons (chevrons,
2143
- arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`) instead of
2144
- \`ml-*\`/\`mr-*\`.
2324
+ Resolve direction with \`client.getStoreDirection(locale)\` \u2014 it returns
2325
+ \`'ltr' | 'rtl'\` for any BCP-47 tag (Arabic, Hebrew, Persian, Urdu, Yiddish
2326
+ today; future RTL locales added by the platform are picked up automatically).
2327
+ Do NOT maintain your own RTL locale set.
2328
+
2329
+ \`\`\`tsx
2330
+ // app/[locale]/layout.tsx
2331
+ const dir = client.getStoreDirection(locale);
2332
+ return <html lang={locale} dir={dir}>...</html>;
2333
+ \`\`\`
2334
+
2335
+ For static rendering, \`storeInfo.i18n.defaultDirection\` carries the store's
2336
+ default direction, and each entry in \`storeInfo.i18n.supportedLocaleObjects\`
2337
+ includes its own \`direction\`.
2338
+
2339
+ Let flexbox reverse automatically once \`<html dir="rtl">\` is set. Do NOT add
2340
+ \`flex-row-reverse\` on top \u2014 that's a double-swap. DO swap directional icons
2341
+ (chevrons, arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`)
2342
+ instead of \`ml-*\`/\`mr-*\`.
2145
2343
 
2146
2344
  ### Language switcher
2147
2345
 
@@ -2518,6 +2716,141 @@ and a \`newsletter\` form embedded in the footer), render each form from its
2518
2716
  own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
2519
2717
  \`createInquiry\` must match.`;
2520
2718
  }
2719
+ function getContentSection() {
2720
+ return `## Content \u2014 typed merchant content store
2721
+
2722
+ Brainerce ships a typed content store so merchants can edit site chrome, FAQ,
2723
+ static pages, and inline rich-text blocks in the dashboard \u2014 without
2724
+ re-prompting the AI that built their storefront. Every row has a \`type\` +
2725
+ \`key\` + typed \`data\` payload + free-form \`customFields\`.
2726
+
2727
+ **Six content types.** Each one has a fixed \`data\` shape; the SDK's TypeScript
2728
+ generics keep them in lockstep:
2729
+
2730
+ | Type | Use for | \`data\` shape (abbreviated) |
2731
+ | -------------- | -------------------------------------- | --------------------------- |
2732
+ | \`FAQ\` | Q/A accordions | \`{ items: { question, answer }[] }\` |
2733
+ | \`FOOTER\` | Site footer (chrome) | \`{ columns, copyright?, social? }\` |
2734
+ | \`HEADER\` | Top nav + logo + CTA (chrome) | \`{ logo?, navItems, cta? }\` |
2735
+ | \`ANNOUNCEMENT\`| Banners; time-bound by \`startsAt/endsAt\` | \`{ message, severity, dismissible, ... }\` |
2736
+ | \`RICH_TEXT\` | Free-form HTML blocks embedded inline | \`{ html }\` |
2737
+ | \`PAGE\` | Static pages with slug + SEO | \`{ slug, title, html, seo? }\` |
2738
+
2739
+ Run \`get-type-definitions\` with \`domain: 'content'\` for the full interfaces.
2740
+
2741
+ ### Default key
2742
+
2743
+ Every type has \`'main'\` as its universal default key. \`client.content.faq.get()\`
2744
+ with no arguments resolves to \`key='main'\`. Topical keys (\`'shipping'\`,
2745
+ \`'holiday-2026'\`, \`'about'\`) are merchant-named.
2746
+
2747
+ ### Reading content (any SDK mode)
2748
+
2749
+ Public reads work in vibe-coded mode, storefront mode, and admin mode. They
2750
+ return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes
2751
+ when the merchant hasn't seeded yet.
2752
+
2753
+ \`\`\`ts
2754
+ // Single entry, default key 'main', resolved to a locale
2755
+ const faq = await client.content.faq.get('main', locale);
2756
+ if (faq) {
2757
+ faq.data.items.forEach(({ question, answer }) => {
2758
+ // Render question + sanitize(answer)
2759
+ });
2760
+ }
2761
+
2762
+ // All entries of a type
2763
+ const allFaqs = await client.content.faq.list(locale);
2764
+
2765
+ // Page by URL slug \u2014 for app/[slug]/page.tsx
2766
+ const page = await client.content.page.getBySlug(slug, locale);
2767
+ if (!page) notFound();
2768
+ \`\`\`
2769
+
2770
+ ### Security \u2014 sanitize HTML before rendering
2771
+
2772
+ \`FAQ.items[i].answer\`, \`RICH_TEXT.html\`, and \`PAGE.html\` carry
2773
+ MERCHANT-AUTHORED HTML. The server does NOT pre-sanitize \u2014 some merchants
2774
+ embed iframes (e.g. YouTube) which strict sanitizers would strip. ALWAYS
2775
+ sanitize on the storefront before injecting:
2776
+
2777
+ \`\`\`ts
2778
+ // Recommended: isomorphic-dompurify
2779
+ import DOMPurify from 'isomorphic-dompurify';
2780
+ const safe = DOMPurify.sanitize(rawHtml);
2781
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
2782
+ \`\`\`
2783
+
2784
+ Skipping this is XSS.
2785
+
2786
+ ### Custom fields
2787
+
2788
+ Every Content row carries a free-form \`customFields: Record<string, string>\`.
2789
+ Merchants add arbitrary key-value extras (\`helpEmail\`, \`phoneNumber\`,
2790
+ \`foundedYear\`) that you can opt into reading:
2791
+
2792
+ \`\`\`ts
2793
+ const faq = await client.content.faq.get('shipping');
2794
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
2795
+ \`\`\`
2796
+
2797
+ The shape is whatever the merchant entered. Read keys you expect; ignore the rest.
2798
+
2799
+ ### Locale resolution
2800
+
2801
+ All public reads accept a \`locale\` argument. The server resolves
2802
+ \`translations[locale]\` server-side and returns the resolved \`data\` payload \u2014
2803
+ the storefront does NOT need to do its own overlay. Empty / missing translations
2804
+ fall through to the default-locale value.
2805
+
2806
+ ### Cache
2807
+
2808
+ Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
2809
+ Merchant edits propagate within ~5 minutes. Don't layer extra client-side
2810
+ caching beyond Next.js's default fetch cache.
2811
+
2812
+ ### Admin writes (apiKey mode)
2813
+
2814
+ \`\`\`ts
2815
+ const adminClient = new BrainerceClient({ apiKey: process.env.BRAINERCE_API_KEY });
2816
+
2817
+ // Create \u2014 always starts in DRAFT
2818
+ const faq = await adminClient.content.faq.create({
2819
+ key: 'shipping',
2820
+ name: 'Shipping FAQ',
2821
+ data: { items: [{ question: 'How long?', answer: 'Most orders ship in 2 days.' }] },
2822
+ });
2823
+
2824
+ // Update (data replaces wholesale; last-write-wins on the data field)
2825
+ await adminClient.content.update(faq.id, {
2826
+ data: { items: [{ question: 'How long?', answer: 'Updated answer.' }] },
2827
+ });
2828
+
2829
+ // Publish / unpublish
2830
+ await adminClient.content.publish(faq.id);
2831
+ await adminClient.content.unpublish(faq.id);
2832
+
2833
+ // Hard delete
2834
+ await adminClient.content.remove(faq.id);
2835
+ \`\`\`
2836
+
2837
+ Write operations throw if called from vibe-coded or storefront mode.
2838
+
2839
+ ### Reserved key convention
2840
+
2841
+ \`'main'\` is reserved as the universal default. Don't use it for topical
2842
+ entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'\`,
2843
+ \`'holiday-2026'\`). The validation rule is \`^[a-z][a-z0-9-]*$\`, max 64 chars.
2844
+
2845
+ ### See also
2846
+
2847
+ - \`get-business-flows\` with \`flow: 'content-bootstrap'\` for the full
2848
+ layout / FAQ / page recipe.
2849
+ - \`get-required-features\` lists each Content surface (\`site-header\`,
2850
+ \`site-footer\`, \`announcement-bar\`, \`faq-page\`, \`static-pages\`).
2851
+ - \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
2852
+ interfaces.`;
2853
+ }
2521
2854
  function getSectionByTopic(topic, connectionId, currency) {
2522
2855
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
2523
2856
  const cur = currency || "USD";
@@ -2564,6 +2897,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2564
2897
  return getAdminApiSection();
2565
2898
  case "inquiries":
2566
2899
  return getContactInquiriesSection();
2900
+ case "content":
2901
+ return getContentSection();
2567
2902
  case "all":
2568
2903
  return [
2569
2904
  "# Brainerce SDK \u2014 full topic dump",
@@ -2652,10 +2987,14 @@ function getSectionByTopic(topic, connectionId, currency) {
2652
2987
  "",
2653
2988
  "---",
2654
2989
  "",
2655
- getContactInquiriesSection()
2990
+ getContactInquiriesSection(),
2991
+ "",
2992
+ "---",
2993
+ "",
2994
+ getContentSection()
2656
2995
  ].join("\n");
2657
2996
  default:
2658
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, all`;
2997
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, all`;
2659
2998
  }
2660
2999
  }
2661
3000
 
@@ -2683,6 +3022,7 @@ var GET_SDK_DOCS_SCHEMA = {
2683
3022
  "i18n",
2684
3023
  "admin",
2685
3024
  "inquiries",
3025
+ "content",
2686
3026
  "all"
2687
3027
  ]).describe("The SDK documentation topic to retrieve"),
2688
3028
  salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
@@ -2693,9 +3033,7 @@ var GET_SDK_DOCS_SCHEMA = {
2693
3033
  async function handleGetSdkDocs(args) {
2694
3034
  const id = args.salesChannelId ?? args.connectionId;
2695
3035
  if (!args.salesChannelId && args.connectionId) {
2696
- console.warn(
2697
- "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2698
- );
3036
+ console.warn("get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead");
2699
3037
  }
2700
3038
  const content = getSectionByTopic(args.topic, id, args.currency);
2701
3039
  return {
@@ -3427,11 +3765,16 @@ interface ProductReviewAdmin extends ProductReview {
3427
3765
  updatedAt: string;
3428
3766
  }
3429
3767
 
3430
- interface SubmitProductReviewInput {
3431
- authorName: string;
3432
- authorEmail?: string; // recommended \u2014 used for guest dedupe + verified-purchase derivation
3768
+ interface WriteProductReviewInput {
3433
3769
  rating: number; // 1-5
3434
- body?: string; // optional
3770
+ body?: string; // optional, max 5000 chars
3771
+ }
3772
+
3773
+ interface MyProductReview {
3774
+ eligible: boolean;
3775
+ // Machine-readable reason when not eligible. null when eligible=true.
3776
+ reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found' | null;
3777
+ myReview: ProductReview | null;
3435
3778
  }
3436
3779
 
3437
3780
  // Each Product carries denormalized review stats:
@@ -3672,6 +4015,156 @@ export interface ModifierValidationError {
3672
4015
  // The cart line then carries:
3673
4016
  // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3674
4017
  // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
4018
+ var CONTENT_TYPES = `// ---- Content (typed merchant content store) ----
4019
+ // Brainerce ships a typed content store so merchants can edit FAQ, footer,
4020
+ // header, announcements, rich text, and static pages in the dashboard
4021
+ // without re-prompting the AI that built the storefront. Every row has a
4022
+ // 'type' + 'key' + typed 'data' payload + free-form 'customFields'.
4023
+ //
4024
+ // SECURITY (read carefully):
4025
+ // RICH_TEXT.html, PAGE.html, and FAQ answers are MERCHANT-AUTHORED HTML.
4026
+ // ALWAYS sanitize with isomorphic-dompurify (or equivalent) before
4027
+ // injecting via dangerouslySetInnerHTML. The server does NOT pre-sanitize
4028
+ // because some merchants embed iframes (e.g. YouTube) which strict
4029
+ // sanitizers would strip; the storefront chooses the policy.
4030
+ //
4031
+ // 404 contract: client.content.<type>.get(key) returns null when no
4032
+ // PUBLISHED row exists. Always render a hard-coded fallback on null so
4033
+ // the page never crashes when the merchant hasn't seeded yet.
4034
+ //
4035
+ // Default key: every type has 'main' as its universal default. Pass no
4036
+ // argument to fetch the main entry; pass a custom key ('shipping',
4037
+ // 'holiday-2026', 'about') for topical entries.
4038
+
4039
+ export type ContentType = 'FAQ' | 'FOOTER' | 'HEADER' | 'ANNOUNCEMENT' | 'RICH_TEXT' | 'PAGE';
4040
+ export type ContentStatus = 'DRAFT' | 'PUBLISHED';
4041
+
4042
+ export interface FaqItem {
4043
+ question: string;
4044
+ /** Sanitized HTML \u2014 sanitize before rendering. */
4045
+ answer: string;
4046
+ }
4047
+ export interface FaqContent { items: FaqItem[] }
4048
+
4049
+ export interface FooterLink { label: string; url: string }
4050
+ export interface FooterColumn { title: string; links: FooterLink[] }
4051
+ export interface FooterSocialLink { platform: string; url: string } // 'instagram' | 'facebook' | 'x' | ...
4052
+ export interface FooterContent {
4053
+ columns: FooterColumn[];
4054
+ copyright?: string;
4055
+ social?: FooterSocialLink[];
4056
+ }
4057
+
4058
+ export interface HeaderLogo { src: string; alt: string }
4059
+ export interface HeaderNavItem { label: string; url: string }
4060
+ export interface HeaderCta { label: string; url: string }
4061
+ export interface HeaderContent {
4062
+ logo?: HeaderLogo;
4063
+ navItems: HeaderNavItem[];
4064
+ cta?: HeaderCta;
4065
+ }
4066
+
4067
+ export type AnnouncementSeverity = 'info' | 'warning' | 'success';
4068
+ export interface AnnouncementContent {
4069
+ message: string;
4070
+ severity: AnnouncementSeverity;
4071
+ dismissible: boolean;
4072
+ /** ISO 8601 \u2014 filter client-side. */
4073
+ startsAt?: string;
4074
+ endsAt?: string;
4075
+ ctaLabel?: string;
4076
+ ctaHref?: string;
4077
+ }
4078
+
4079
+ export interface RichTextContent {
4080
+ /** Raw HTML \u2014 sanitize before rendering. */
4081
+ html: string;
4082
+ }
4083
+
4084
+ export interface PageSeo {
4085
+ title?: string;
4086
+ description?: string;
4087
+ ogImage?: string;
4088
+ }
4089
+ export interface PageContent {
4090
+ /** URL slug, lower-kebab. */
4091
+ slug: string;
4092
+ title: string;
4093
+ /** Raw HTML \u2014 sanitize before rendering. */
4094
+ html: string;
4095
+ seo?: PageSeo;
4096
+ }
4097
+
4098
+ export interface ContentSummary {
4099
+ id: string;
4100
+ type: ContentType;
4101
+ key: string;
4102
+ name: string;
4103
+ status: ContentStatus;
4104
+ position: number;
4105
+ updatedAt: string;
4106
+ }
4107
+
4108
+ export interface Content<T extends ContentType = ContentType> extends ContentSummary {
4109
+ type: T;
4110
+ data: T extends 'FAQ' ? FaqContent
4111
+ : T extends 'FOOTER' ? FooterContent
4112
+ : T extends 'HEADER' ? HeaderContent
4113
+ : T extends 'ANNOUNCEMENT' ? AnnouncementContent
4114
+ : T extends 'RICH_TEXT' ? RichTextContent
4115
+ : T extends 'PAGE' ? PageContent
4116
+ : never;
4117
+ /** Free-form merchant-defined extras. Read keys the merchant told you to expect. */
4118
+ customFields: Record<string, string>;
4119
+ salesChannelIds: string[];
4120
+ }
4121
+
4122
+ // ---- SDK usage examples ----
4123
+ //
4124
+ // FAQ \u2014 render an accordion from the main FAQ (or a topical one):
4125
+ // const faq = await client.content.faq.get('main', locale); // 'shipping', 'returns', ...
4126
+ // if (faq) {
4127
+ // faq.data.items.forEach(({ question, answer }) => {
4128
+ // // Render question + sanitize(answer) \u2014 never inject raw HTML.
4129
+ // });
4130
+ // }
4131
+ //
4132
+ // Footer \u2014 server component in root layout:
4133
+ // const footer = await client.content.footer.get('main', locale);
4134
+ // if (!footer) return <Fallback />;
4135
+ // // Render footer.data.columns, footer.data.social, footer.data.copyright
4136
+ //
4137
+ // Header \u2014 same pattern as footer:
4138
+ // const header = await client.content.header.get('main', locale);
4139
+ //
4140
+ // Announcement \u2014 multiple may be active; filter by date client-side:
4141
+ // const announcements = await client.content.announcement.list(locale);
4142
+ // const now = Date.now();
4143
+ // const active = announcements.filter((a) => {
4144
+ // const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
4145
+ // const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
4146
+ // return startOk && endOk;
4147
+ // });
4148
+ //
4149
+ // Rich text \u2014 inline block anywhere on a page:
4150
+ // const block = await client.content.richText.get('about-intro', locale);
4151
+ // <div dangerouslySetInnerHTML={{ __html: sanitize(block.data.html) }} />
4152
+ //
4153
+ // Page \u2014 catch-all route by slug (e.g. /about, /terms, /privacy):
4154
+ // // app/[slug]/page.tsx
4155
+ // const page = await client.content.page.getBySlug(params.slug, locale);
4156
+ // if (!page) notFound();
4157
+ // // page.data.title, page.data.html, page.data.seo
4158
+ // return <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />;
4159
+ //
4160
+ // Custom fields \u2014 every Content row carries a free-form Record<string, string>:
4161
+ // const faq = await client.content.faq.get('shipping');
4162
+ // <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
4163
+ //
4164
+ // Cache \u2014 public reads carry Cache-Control: public, max-age=300,
4165
+ // stale-while-revalidate=60. Storefront changes propagate within ~5 min
4166
+ // of the merchant publishing. Do not add extra client-side caching
4167
+ // beyond Next.js's default fetch cache.`;
3675
4168
  var TYPES_BY_DOMAIN = {
3676
4169
  products: PRODUCTS_TYPES,
3677
4170
  cart: CART_TYPES,
@@ -3682,7 +4175,8 @@ var TYPES_BY_DOMAIN = {
3682
4175
  helpers: HELPERS_TYPES,
3683
4176
  inquiries: INQUIRIES_TYPES,
3684
4177
  reviews: REVIEWS_TYPES,
3685
- "modifier-groups": MODIFIER_GROUPS_TYPES
4178
+ "modifier-groups": MODIFIER_GROUPS_TYPES,
4179
+ content: CONTENT_TYPES
3686
4180
  };
3687
4181
  function getTypesByDomain(domain) {
3688
4182
  if (domain === "all") {
@@ -3713,9 +4207,10 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
3713
4207
  "helpers",
3714
4208
  "inquiries",
3715
4209
  "reviews",
4210
+ "content",
3716
4211
  "all"
3717
4212
  ]).describe(
3718
- 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
4213
+ 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page.'
3719
4214
  )
3720
4215
  };
3721
4216
  async function handleGetTypeDefinitions(args) {
@@ -3734,6 +4229,7 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3734
4229
  "sdk-init",
3735
4230
  "cart-read-and-mutate",
3736
4231
  "variant-selection",
4232
+ "variant-selector-swatches",
3737
4233
  "checkout-address-and-shipping",
3738
4234
  "checkout-payment-providers",
3739
4235
  "checkout-stripe-confirm",
@@ -3803,28 +4299,148 @@ for (const item of cart.items) {
3803
4299
  const unitPrice = parseFloat(item.unitPrice); // prices are strings!
3804
4300
  }`,
3805
4301
  "variant-selection": `// Variant selection with live stock + price updates.
4302
+ // Variants expose attributes as a flat object: { color: 'Red', size: 'M' }.
4303
+ // NOT 'options' \u2014 that field does not exist on ProductVariant.
3806
4304
  import { getVariantPrice, getStockStatus, getVariantOptions } from 'brainerce';
3807
4305
  import type { Product, ProductVariant } from 'brainerce';
3808
4306
 
3809
4307
  function selectVariant(product: Product, selections: Record<string, string>) {
3810
- // selections = { Size: 'M', Color: 'Red' }
3811
- const variant = product.variants.find((v) =>
3812
- v.options.every((o) => selections[o.name] === o.value)
4308
+ // selections = { size: 'M', color: 'Red' } (keys match variant.attributes keys)
4309
+ const variant = product.variants?.find((v) =>
4310
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
3813
4311
  );
3814
4312
  if (!variant) return null;
3815
4313
 
3816
- const price = getVariantPrice(product, variant); // handles compare-at, currency
3817
- const stock = getStockStatus(variant); // 'IN_STOCK' | 'LOW_STOCK' | 'OUT_OF_STOCK'
3818
- const canPurchase = stock !== 'OUT_OF_STOCK';
4314
+ const price = getVariantPrice(variant, product.basePrice); // string, fallback-aware
4315
+ const stock = getStockStatus(variant.inventory); // 'in-stock' | 'low-stock' | 'out-of-stock' | 'unavailable'
4316
+ const canPurchase = variant.inventory?.canPurchase !== false;
3819
4317
 
3820
4318
  // Switch the main product image to the variant's image if it has one
3821
- const image = variant.image ?? product.images[0];
4319
+ const image = variant.image ?? product.images?.[0];
3822
4320
 
3823
4321
  return { variant, price, stock, canPurchase, image };
3824
4322
  }
3825
4323
 
3826
- // Build the option picker from getVariantOptions(product) \u2014 returns
3827
- // [{ name: 'Size', values: ['S','M','L'] }, ...]`,
4324
+ // Build the option picker by iterating product.variants and grouping
4325
+ // variant.attributes into { color: ['Red', 'Blue'], size: ['S','M','L'] }.
4326
+ // For each variant you can also call getVariantOptions(variant) which returns
4327
+ // the same key/value pairs as an array with translated names when setLocale() is active.
4328
+ // For swatch metadata (color hex, dual-color, image), use the
4329
+ // 'variant-selector-swatches' operation instead.`,
4330
+ "variant-selector-swatches": `// Variant picker that mixes color swatches and text buttons in one product.
4331
+ // Uses product.productAttributeOptions[] \u2014 the merchant-configured swatch
4332
+ // metadata. displayType is the AttributeDisplayType Prisma enum, one of:
4333
+ // 'DEFAULT' \u2014 plain text button
4334
+ // 'COLOR_SWATCH' \u2014 swatchColor (+ optional swatchColor2 dual-color gradient)
4335
+ // 'IMAGE_SWATCH' \u2014 swatchImageUrl thumbnail
4336
+ // 'MIXED_SWATCH' \u2014 per-option hybrid: image if swatchImageUrl is set,
4337
+ // otherwise fall back to swatchColor
4338
+ // getProductSwatches() groups options by attribute name so you can render each
4339
+ // attribute with its own displayType \u2014 a single product can have Color as
4340
+ // swatches AND Size as text buttons.
4341
+ import { getProductSwatches } from 'brainerce';
4342
+ import type { Product } from 'brainerce';
4343
+
4344
+ function VariantPicker({
4345
+ product,
4346
+ selections,
4347
+ onSelect,
4348
+ }: {
4349
+ product: Product;
4350
+ selections: Record<string, string>;
4351
+ onSelect: (attrName: string, value: string) => void;
4352
+ }) {
4353
+ const groups = getProductSwatches(product);
4354
+ // groups: [{ attributeName, displayType, options: [{ name, swatchColor, swatchColor2, swatchImageUrl }] }]
4355
+
4356
+ return (
4357
+ <>
4358
+ {groups.map((group) => (
4359
+ <div key={group.attributeName}>
4360
+ <label>{group.attributeName}: {selections[group.attributeName] ?? ''}</label>
4361
+ <div style={{ display: 'flex', gap: 8 }}>
4362
+ {group.options.map((opt) => {
4363
+ const selected = selections[group.attributeName] === opt.name;
4364
+ const onClick = () => onSelect(group.attributeName, opt.name);
4365
+
4366
+ // COLOR_SWATCH: round button. swatchColor2 = dual-color gradient.
4367
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
4368
+ const bg = opt.swatchColor2
4369
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4370
+ : opt.swatchColor;
4371
+ return (
4372
+ <button
4373
+ key={opt.name}
4374
+ type="button"
4375
+ title={opt.name}
4376
+ aria-pressed={selected}
4377
+ onClick={onClick}
4378
+ style={{
4379
+ width: 36,
4380
+ height: 36,
4381
+ borderRadius: '50%',
4382
+ background: bg,
4383
+ outline: selected ? '2px solid black' : 'none',
4384
+ }}
4385
+ />
4386
+ );
4387
+ }
4388
+
4389
+ // IMAGE_SWATCH: square thumbnail.
4390
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
4391
+ return (
4392
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4393
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4394
+ </button>
4395
+ );
4396
+ }
4397
+
4398
+ // MIXED_SWATCH: per-option hybrid (image wins if present).
4399
+ if (group.displayType === 'MIXED_SWATCH') {
4400
+ if (opt.swatchImageUrl) {
4401
+ return (
4402
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4403
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4404
+ </button>
4405
+ );
4406
+ }
4407
+ if (opt.swatchColor) {
4408
+ const bg = opt.swatchColor2
4409
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4410
+ : opt.swatchColor;
4411
+ return (
4412
+ <button
4413
+ key={opt.name}
4414
+ type="button"
4415
+ title={opt.name}
4416
+ aria-pressed={selected}
4417
+ onClick={onClick}
4418
+ style={{ width: 36, height: 36, borderRadius: '50%', background: bg }}
4419
+ />
4420
+ );
4421
+ }
4422
+ }
4423
+
4424
+ // DEFAULT (or any swatch type missing its data): text button.
4425
+ return (
4426
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4427
+ {opt.name}
4428
+ </button>
4429
+ );
4430
+ })}
4431
+ </div>
4432
+ </div>
4433
+ ))}
4434
+ </>
4435
+ );
4436
+ }
4437
+
4438
+ // After the user picks a value, find the matching ProductVariant:
4439
+ // product.variants?.find((v) =>
4440
+ // Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
4441
+ // )
4442
+ // Then read variant.price, variant.image, variant.inventory.canPurchase
4443
+ // to update the rest of the PDP.`,
3828
4444
  "checkout-address-and-shipping": `// Step 1-3 of the checkout flow. Never reorder or skip.
3829
4445
  import { client } from './brainerce';
3830
4446
 
@@ -4141,8 +4757,10 @@ client.setLocale(locale);
4141
4757
  // order bumps, search suggestions, discount banners, nudges,
4142
4758
  // badges, order history.
4143
4759
 
4144
- // For RTL locales (he, ar), set the document direction.
4145
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
4760
+ // For RTL direction, do not hardcode the locale list. Ask the SDK:
4761
+ // const dir = client.getStoreDirection(currentLocale); // 'ltr' | 'rtl'
4762
+ // document.documentElement.setAttribute('dir', dir);
4763
+ // (Or in React: <html dir={dir}>...</html>.)`,
4146
4764
  "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
4147
4765
  // already returns \u2014 not just order number / total / status.
4148
4766
  //
@@ -4617,21 +5235,25 @@ function renderCartItem(item: CartItem): string {
4617
5235
  function lineTotal(item: CartItem): number {
4618
5236
  return item.unitPrice * item.quantity;
4619
5237
  }`,
4620
- "product-reviews": `// PDP: list visible reviews + submit form + JSON-LD aggregateRating
4621
- import { client } from '@/lib/brainerce';
4622
- import type { Product, ProductReview, SubmitProductReviewInput } from 'brainerce';
4623
-
5238
+ "product-reviews": `// Purchaser-only reviews. Customer must be logged in AND have purchased
5239
+ // the product. The component switches between sign-in CTA / not-eligible /
5240
+ // submit form / edit form based on getMyProductReview().
5241
+ import { getClient, getServerClient } from '@/lib/brainerce';
5242
+ import { checkAuthStatus } from '@/lib/auth';
5243
+ import type { Product, ProductReview, MyProductReview } from 'brainerce';
5244
+
5245
+ // Server component \u2014 fetches existing reviews + emits JSON-LD aggregateRating.
4624
5246
  export async function ProductReviewsSection({ product }: { product: Product }) {
4625
- const { data } = await client.listProductReviews(product.id, { page: 1, limit: 20 });
5247
+ const { data } = await getServerClient().listProductReviews(product.id, { page: 1, limit: 20 });
4626
5248
 
4627
5249
  return (
4628
5250
  <section>
4629
5251
  <h2>Reviews ({product.reviewCount ?? 0})</h2>
4630
- {data.length === 0 && <p>No reviews yet \u2014 be the first.</p>}
5252
+ {data.length === 0 && <p>No reviews yet.</p>}
4631
5253
  {data.map((r) => (
4632
5254
  <article key={r.id}>
4633
5255
  <strong>{r.authorName}</strong>
4634
- {r.verifiedPurchase && <span> \xB7 Verified</span>}
5256
+ {r.verifiedPurchase && <span> \xB7 Verified purchase</span>}
4635
5257
  <div>{'\u2605'.repeat(r.rating)}{'\u2606'.repeat(5 - r.rating)}</div>
4636
5258
  {r.body && <p>{r.body}</p>}
4637
5259
  </article>
@@ -4664,42 +5286,83 @@ function productJsonLd(product: Product, url: string) {
4664
5286
 
4665
5287
  // Client-side form
4666
5288
  'use client';
4667
- import { useState } from 'react';
5289
+ import { useEffect, useState } from 'react';
5290
+
5291
+ type Stage =
5292
+ | { kind: 'loading' }
5293
+ | { kind: 'signed_out' }
5294
+ | { kind: 'not_eligible'; reason: MyProductReview['reason'] }
5295
+ | { kind: 'submit' }
5296
+ | { kind: 'edit'; review: ProductReview };
4668
5297
 
4669
5298
  function ReviewForm({ productId }: { productId: string }) {
5299
+ const [stage, setStage] = useState<Stage>({ kind: 'loading' });
4670
5300
  const [rating, setRating] = useState(5);
4671
5301
  const [body, setBody] = useState('');
4672
- const [name, setName] = useState('');
4673
- const [email, setEmail] = useState('');
4674
5302
  const [error, setError] = useState<string | null>(null);
4675
5303
 
5304
+ useEffect(() => {
5305
+ (async () => {
5306
+ const auth = await checkAuthStatus();
5307
+ if (!auth.isLoggedIn) return setStage({ kind: 'signed_out' });
5308
+ const me = await getClient().getMyProductReview(productId);
5309
+ if (!me.eligible) return setStage({ kind: 'not_eligible', reason: me.reason });
5310
+ if (me.myReview) {
5311
+ setRating(me.myReview.rating);
5312
+ setBody(me.myReview.body ?? '');
5313
+ return setStage({ kind: 'edit', review: me.myReview });
5314
+ }
5315
+ setStage({ kind: 'submit' });
5316
+ })();
5317
+ }, [productId]);
5318
+
5319
+ if (stage.kind === 'loading') return <p>Loading\u2026</p>;
5320
+ if (stage.kind === 'signed_out')
5321
+ return <p><a href="/account/login">Sign in</a> to leave a review.</p>;
5322
+ if (stage.kind === 'not_eligible')
5323
+ return <p>Only customers who purchased this product can leave a review.</p>;
5324
+
4676
5325
  async function submit(e: React.FormEvent) {
4677
5326
  e.preventDefault();
4678
5327
  setError(null);
5328
+ const client = getClient();
5329
+ const input = { rating, body: body || undefined };
4679
5330
  try {
4680
- await client.submitProductReview(productId, {
4681
- authorName: name,
4682
- authorEmail: email,
4683
- rating,
4684
- body: body || undefined,
4685
- });
5331
+ if (stage.kind === 'edit') {
5332
+ await client.updateMyProductReview(productId, input);
5333
+ } else {
5334
+ await client.submitProductReview(productId, input);
5335
+ }
4686
5336
  window.location.reload();
4687
5337
  } catch (err: any) {
4688
- if (err?.status === 409) setError("You've already reviewed this product.");
5338
+ if (err?.status === 403) setError('Only customers who purchased this product can leave a review.');
5339
+ else if (err?.status === 409) setError('You already reviewed this product.');
4689
5340
  else if (err?.status === 429) setError('Too many submissions. Please wait a moment.');
4690
- else setError('Could not submit review. Please try again.');
5341
+ else setError('Could not save your review. Please try again.');
4691
5342
  }
4692
5343
  }
4693
5344
 
5345
+ async function remove() {
5346
+ if (!confirm('Delete your review?')) return;
5347
+ await getClient().deleteMyProductReview(productId);
5348
+ window.location.reload();
5349
+ }
5350
+
4694
5351
  return (
4695
5352
  <form onSubmit={submit}>
4696
- <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" required maxLength={100} />
4697
- <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
4698
- <select value={rating} onChange={(e) => setRating(Number(e.target.value))}>
4699
- {[5,4,3,2,1].map(n => <option key={n} value={n}>{'\u2605'.repeat(n)}</option>)}
4700
- </select>
4701
- <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} placeholder="Tell us what you think (optional)" />
4702
- <button type="submit">Submit review</button>
5353
+ <h3>{stage.kind === 'edit' ? 'Edit your review' : 'Write a review'}</h3>
5354
+ <div>
5355
+ {[1,2,3,4,5].map(n => (
5356
+ <button type="button" key={n} onClick={() => setRating(n)}>
5357
+ {n <= rating ? '\u2605' : '\u2606'}
5358
+ </button>
5359
+ ))}
5360
+ </div>
5361
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} />
5362
+ <button type="submit">{stage.kind === 'edit' ? 'Save changes' : 'Submit review'}</button>
5363
+ {stage.kind === 'edit' && (
5364
+ <button type="button" onClick={remove}>Delete review</button>
5365
+ )}
4703
5366
  {error && <p role="alert">{error}</p>}
4704
5367
  </form>
4705
5368
  );
@@ -5189,7 +5852,7 @@ var RULES = {
5189
5852
  body: `- NEVER hardcode currency, locale, or language strings. Read them from \`get-store-info\` / \`get-store-capabilities\` and use the configured values.
5190
5853
  - NEVER format prices with \`toFixed(2)\` or custom logic. Use \`formatPrice()\` from the SDK \u2014 it honors the store's currency and locale.
5191
5854
  - When the store has i18n enabled (\`capabilities.store.i18n.enabled === true\`), you MUST call \`client.setLocale(locale)\` at app init and include a language switcher. All SDK reads will then return localized content automatically.
5192
- - For RTL locales (\`he\`, \`ar\`), set the document direction to RTL. Do not manually reverse flex layouts \u2014 the platform's CSS reversal handles it.`
5855
+ - For RTL direction, do NOT maintain a local list of RTL locales. Call \`client.getStoreDirection(locale)\` \u2014 it returns \`'ltr' | 'rtl'\` for any BCP-47 tag (covers Arabic, Hebrew, Persian, Urdu, Yiddish, and any future RTL locales the platform adds). Set \`<html dir={...}>\` from this value. The platform's CSS reversal handles flex layouts \u2014 do not manually swap them.`
5193
5856
  },
5194
5857
  types: {
5195
5858
  title: "Type safety",
@@ -5237,6 +5900,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
5237
5900
  "cart-persistence",
5238
5901
  "inventory-reservation",
5239
5902
  "product-customization",
5903
+ "content-bootstrap",
5240
5904
  "all"
5241
5905
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
5242
5906
  };
@@ -5427,6 +6091,76 @@ Server-side guardrails that WILL reject bad requests (so validate client-side to
5427
6091
  - More than 10 uploads per IP per minute \u2192 429.
5428
6092
 
5429
6093
  Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
6094
+ },
6095
+ "content-bootstrap": {
6096
+ title: "Content Bootstrap \u2014 site chrome & static content",
6097
+ body: `Every Brainerce storefront should render merchant-defined site chrome (header, footer, announcements, FAQ, static pages) from the Content API. The merchant edits these in the Brainerce dashboard; storefronts pick up changes within ~5 minutes (public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`).
6098
+
6099
+ 1. **Fetch chrome at the root layout** (server component if Next.js). All three return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes when the merchant hasn't seeded yet.
6100
+ \`\`\`ts
6101
+ const [header, footer, announcements] = await Promise.all([
6102
+ client.content.header.get('main', locale),
6103
+ client.content.footer.get('main', locale),
6104
+ client.content.announcement.list(locale),
6105
+ ]);
6106
+ \`\`\`
6107
+
6108
+ 2. **FAQ \u2014 fetch lazily on the FAQ page.** Default key is \`'main'\`; pass a topical key (\`'shipping'\`, \`'returns'\`) for sub-FAQs.
6109
+ \`\`\`ts
6110
+ const faq = await client.content.faq.get('main', locale);
6111
+ if (faq) {
6112
+ faq.data.items.forEach(({ question, answer }) => {
6113
+ // sanitize(answer) \u2014 see step 4
6114
+ });
6115
+ }
6116
+ \`\`\`
6117
+
6118
+ 3. **Static pages \u2014 catch-all route by slug:**
6119
+ \`\`\`tsx
6120
+ // app/[slug]/page.tsx
6121
+ export default async function Page({ params }) {
6122
+ const page = await client.content.page.getBySlug(params.slug, locale);
6123
+ if (!page) notFound();
6124
+ return (
6125
+ <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />
6126
+ );
6127
+ }
6128
+ \`\`\`
6129
+
6130
+ 4. **SECURITY \u2014 sanitize HTML before rendering.** \`FAQ.items[i].answer\`, \`PAGE.html\`, and \`RICH_TEXT.html\` are merchant-authored HTML. The server does NOT pre-sanitize because some merchants embed iframes (e.g. YouTube). Always sanitize at the edge of your render:
6131
+ \`\`\`ts
6132
+ import DOMPurify from 'isomorphic-dompurify';
6133
+ const safe = DOMPurify.sanitize(rawHtml);
6134
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
6135
+ \`\`\`
6136
+ Skipping this is XSS.
6137
+
6138
+ 5. **Announcements \u2014 multiple may be active; filter by date client-side:**
6139
+ \`\`\`ts
6140
+ const now = Date.now();
6141
+ const visible = announcements.filter((a) => {
6142
+ const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
6143
+ const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
6144
+ return startOk && endOk;
6145
+ });
6146
+ \`\`\`
6147
+
6148
+ 6. **RTL direction \u2014 call \`client.getStoreDirection(locale)\`:**
6149
+ \`\`\`tsx
6150
+ const dir = client.getStoreDirection(locale);
6151
+ <html lang={locale} dir={dir}>...</html>
6152
+ \`\`\`
6153
+ Do NOT maintain a local RTL locale set \u2014 the SDK helper covers Arabic / Hebrew / Persian / Urdu / Yiddish today and picks up any future RTL locale automatically.
6154
+
6155
+ 7. **Custom fields \u2014 every Content row has free-form \`customFields: Record<string, string>\`.** Read keys the merchant told you to expect:
6156
+ \`\`\`ts
6157
+ const faq = await client.content.faq.get('shipping');
6158
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
6159
+ \`\`\`
6160
+
6161
+ 8. **Cache:** public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`. Don't add extra client-side caching beyond Next.js's default fetch cache \u2014 merchants expect their edits to appear within ~5 minutes.
6162
+
6163
+ **Translations.** All public reads accept a \`locale\` argument; the server resolves \`translations[locale]\` server-side. Empty / missing overlays fall through to the default-locale value. The storefront does NOT need to do its own per-field overlay \u2014 call with the active locale and render what comes back.`
5430
6164
  }
5431
6165
  };
5432
6166
  var FLOW_ORDER = [
@@ -5438,7 +6172,8 @@ var FLOW_ORDER = [
5438
6172
  "order-confirmation",
5439
6173
  "cart-persistence",
5440
6174
  "inventory-reservation",
5441
- "product-customization"
6175
+ "product-customization",
6176
+ "content-bootstrap"
5442
6177
  ];
5443
6178
  async function handleGetBusinessFlows(args) {
5444
6179
  const header = "# Brainerce Business Flows\n\nThese sequences are framework-neutral and non-negotiable. Your framework and file layout are your choice \u2014 the order of SDK calls and the error handling is not.";
@@ -5507,9 +6242,9 @@ var FEATURES = [
5507
6242
  },
5508
6243
  {
5509
6244
  id: "product-reviews",
5510
- title: "Display + collect product reviews with stars + JSON-LD",
5511
- description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name, verified-purchase badge, body, and date. Include a submit form (name + email + 1-5 stars + optional body). On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; the merchant moderates from the admin surface. Rate-limited to 3 submits / 60s / IP. Show a friendly "you already reviewed this" message on 409.',
5512
- sdk: "client.listProductReviews(productId), client.submitProductReview(productId, { authorName, authorEmail, rating, body }). Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
6245
+ title: "Display + collect product reviews (purchaser-only) with stars + JSON-LD",
6246
+ description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name (from customer profile), verified-purchase badge, body, and date \u2014 public, no login needed. Below the list, a form that adapts to the current customer: signed-in + purchased + no review yet \u2192 submit form (rating 1-5 + optional body, no name/email \u2014 those are derived from the customer profile); signed-in + purchased + already has review \u2192 edit form prefilled with rating/body plus a delete button; signed-in but did NOT purchase \u2192 "only customers who purchased this product can leave a review"; not signed in \u2192 sign-in CTA. Eligibility: physical products require an order in SHIPPED+; downloadable products additionally accept PAID/PROCESSING. On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; merchants moderate (hide/show) from the admin surface. Rate-limited 3 submits / 60s / IP.',
6247
+ sdk: "client.listProductReviews(productId) for the public list; client.getMyProductReview(productId) for the form-state decision; client.submitProductReview / updateMyProductReview / deleteMyProductReview for the three customer actions. All four customer methods require setCustomerToken(...) after login. Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
5513
6248
  mandatory: "mandatory"
5514
6249
  },
5515
6250
  {
@@ -5650,11 +6385,57 @@ var FEATURES = [
5650
6385
  {
5651
6386
  id: "i18n",
5652
6387
  title: "Serve multiple languages with a language switcher",
5653
- description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders RTL locales (he, ar) with the correct document direction.",
5654
- sdk: "client.setLocale(locale). Read supported locales from get-store-capabilities.store.i18n.",
6388
+ description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders the correct document direction by reading client.getStoreDirection(locale) \u2014 do not hardcode an RTL locale set.",
6389
+ sdk: "client.setLocale(locale). client.getStoreDirection(locale) for <html dir>. Read supported locales from get-store-capabilities.store.i18n.",
5655
6390
  mandatory: "conditional",
5656
6391
  capabilityFlag: "i18n",
5657
6392
  whenDisabledNote: "This store is single-language. Do not build the language switcher."
6393
+ },
6394
+ {
6395
+ id: "site-header",
6396
+ title: "Site header from merchant content (logo + nav + CTA)",
6397
+ description: 'Fetch client.content.header.get("main", locale) in the root layout. Returns null when the merchant has not seeded yet \u2014 render a hard-coded fallback so the page never crashes. Renders header.data.logo, header.data.navItems[], header.data.cta if present.',
6398
+ sdk: 'client.content.header.get("main", locale)',
6399
+ flowRef: "content-bootstrap",
6400
+ mandatory: "mandatory"
6401
+ },
6402
+ {
6403
+ id: "site-footer",
6404
+ title: "Site footer from merchant content (columns + social + copyright)",
6405
+ description: 'Fetch client.content.footer.get("main", locale) in the root layout. Returns null when unseeded \u2014 render a hard-coded fallback. Render footer.data.columns[].links, footer.data.social[], footer.data.copyright.',
6406
+ sdk: 'client.content.footer.get("main", locale)',
6407
+ flowRef: "content-bootstrap",
6408
+ mandatory: "mandatory"
6409
+ },
6410
+ {
6411
+ id: "announcement-bar",
6412
+ title: "Announcement bar at the top of every page",
6413
+ description: "Fetch client.content.announcement.list(locale) in the root layout. Filter by data.startsAt / data.endsAt client-side. Render a dismissible bar when data.dismissible=true. Build the UI anyway \u2014 it auto-hides when no announcements exist.",
6414
+ sdk: "client.content.announcement.list(locale)",
6415
+ flowRef: "content-bootstrap",
6416
+ mandatory: "conditional",
6417
+ capabilityFlag: "hasContent",
6418
+ whenDisabledNote: "Store has no published Content rows yet. Build the announcement bar anyway \u2014 it auto-hides on empty."
6419
+ },
6420
+ {
6421
+ id: "faq-page",
6422
+ title: "FAQ page rendered from merchant content",
6423
+ description: 'Build /faq as an accordion fed by client.content.faq.get("main", locale). For topical FAQs, use a key parameter (shipping, returns, ...). Always sanitize answer HTML before injecting via dangerouslySetInnerHTML. Build the page anyway \u2014 it auto-hides or 404s when no FAQ rows exist.',
6424
+ sdk: 'client.content.faq.get("main", locale), client.content.faq.list(locale)',
6425
+ flowRef: "content-bootstrap",
6426
+ mandatory: "conditional",
6427
+ capabilityFlag: "hasContent",
6428
+ whenDisabledNote: "No FAQ content yet. Build /faq anyway \u2014 it auto-hides on empty."
6429
+ },
6430
+ {
6431
+ id: "static-pages",
6432
+ title: "Static pages from merchant content (About, Terms, Privacy, \u2026)",
6433
+ description: "Mount a catch-all app/[slug]/page.tsx route. Inside, call client.content.page.getBySlug(params.slug, locale). On null \u2192 notFound(). On hit, sanitize page.data.html before injecting via dangerouslySetInnerHTML. Generate <Metadata> from page.data.seo. Build the route anyway \u2014 it 404s on unknown slugs.",
6434
+ sdk: "client.content.page.getBySlug(slug, locale), client.content.page.list(locale)",
6435
+ flowRef: "content-bootstrap",
6436
+ mandatory: "conditional",
6437
+ capabilityFlag: "hasContent",
6438
+ whenDisabledNote: "No static pages yet. Build the catch-all route anyway \u2014 it 404s on unknown slugs."
5658
6439
  }
5659
6440
  ];
5660
6441
  function isFeatureActive(feature, caps) {
@@ -5705,6 +6486,7 @@ function renderCapabilitiesSummary(caps) {
5705
6486
  );
5706
6487
  lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
5707
6488
  lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
6489
+ lines.push(`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`);
5708
6490
  lines.push(
5709
6491
  `- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
5710
6492
  );